markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Success! It definitely looksl like scattered moonlight is responsible for the bulk of the added sky brightness. But there's also a portion of data where the moon was bright but the sky was still dark. There's more to it than just phase. Now we turn to the task of fitting a model to this. 2) The ModelTurns out that the... | import numpy as np
jj,ii = np.indices((1024,1024))/1024 # 2D index arrays scaled 0->1
rho = np.sqrt((ii-0.5)**2 + (jj-0.5)**2)*45.0 # 2D array of angles from center in degrees
f = 10**5.36*(1.06 + (np.cos(rho*np.pi/180)**2)) + np.power(10, 6.15-rho/40)
plt.imshow(f, origin='lower', extent=(-22.5,22.5,... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
So there's less and less scattered light farther from the moon (at the center). But this scattered light is also attenuated (absorbed) by the atmosphere. This attenuation is parametrized by the *airmass* $X$, the relative amount of atmosphere the light has to penetrate (with $X=1$ for the zenith). Krisciunas & Schaefer... | def X(Z):
'''Airmass as afunction zenith angle Z in radians'''
return 1./np.sqrt(1 - 0.96*np.power(np.sin(Z),2))
Z = (45 - jj*45)*np.pi/180. # rescale jj (0->1) to Z (45->0) and convert to radians
plt.imshow(f*np.power(10, -0.4*5*X(Z)), origin='lower', extent=(-22.5,22.5,45,0))
plt.contour(f*np.power(10, -0... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
So as we get closer to the horizon, there's less moonlight, as it's been attenuated by the larger amount of atmosphere. Lastly, to convert these nanoLamberts into magnitudes per square arc-second, we need the dark (no moon) sky brightness at the zenith, $m_{dark}$, and convert that to nanoLamberts using this formula:$$... | def modelsky(alpha, rho, kx, Z, Zm, mdark):
Istar = np.power(10, -0.4*(3.84+0.026*np.absolute(alpha)+4e-9*np.power(alpha,4)))
frho = np.power(10, 5.36)*(1.06 + np.power(np.cos(rho),2))+np.power(10, 6.15-rho*180./np.pi/40)
Bmoon = frho*Istar*np.power(10,-0.4*kx*X(Zm))*(1-np.power(10,-0.4*kx*X(Z)))
Bdark ... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
Note that all angles should be entered in radians to work with `numpy` trig functions. 3) Data MungingNow, we just need the final ingredients: $\alpha$, $\rho$, $Z$, and $Z_m$, all of which are computed using `astropy.coordinates`. The lunar phase angle $\alpha$ is defined as the angular separation between the Earth ... | alpha = (180. - data['phase']) # Note: these need to be in degrees
data['alpha'] = pd.Series(alpha, index=data.index) | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
Next, in order to compute zenith angles and azimuths, we need to tell the `astropy` functions where on Earth we are located, since these quantities depend on our local horizon. Luckily, Las Campanas Observatory (LCO) is in `astropy`'s database of locations. We'll also need to create locations on the sky for all our bac... | from astropy.coordinates import EarthLocation, SkyCoord, AltAz
from astropy import units as u
lco = EarthLocation.of_site('lco')
fields = SkyCoord(data['RA']*u.degree, data['Decl']*u.degree) # astropy often requires units
f_altaz = fields.transform_to(AltAz(obstime=times, location=lco)) # Transform from RA/... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
I've added the variables to the Pandas `dataFrame` as it will help with plotting later. We can try plotting some of these variables against others to see how things look. Let's try a scatter plot of moon/sky separation vs. sky brightness and color the points according to lunar phase. I tried this with the Pandas `scat... | fig,axes = plt.subplots(1,2, figsize=(15,6))
sc = axes[0].scatter(data['rho'], data['magsky'], marker='.', c=data['alpha'], cmap='viridis_r')
axes[0].set_xlabel(r'$\rho$', fontsize=16)
axes[0].set_ylabel('Sky brightness (mag/sq-arc-sec)', fontsize=12)
axes[0].text(1.25, 0.5, "lunar phase", va='center', ha='right', rota... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
There certainly seems to be a trend that the closer to full ($\alpha = 0$, yellow), the brighter the background and the closer the moon is to the field (lower $\rho$), the higher the background. Looks good. 4) Fitting (Training) the ModelLet's try and fit this data with our model and solve for $m_{dark}$, and $k_x$, t... | from scipy.optimize import leastsq
def func(p, alpha, rho, Z, Zm, magsky):
mdark,kx = p
return magsky - modelsky(alpha, rho, kx, Z, Zm, mdark) | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
We now run the least-squares function, which will find the parameters `p` which minimize the squared sum of the residuals (i.e. $\chi^2$). `leastsq` takes as arguments the function we wrote above, `func`, an initial guess of the parameters, and a tuple of extra arguments needed by our function. It returns the best-fit ... | pars,stat = leastsq(func, [22, 0.2], args=(data['alpha'],data['rho'],data['Z'],data['Zm'],data['magsky']))
print(pars)
# save the best-fit model and residuals
data['modelsky']=pd.Series(modelsky(data['alpha'],data['rho'],pars[1],data['Z'],data['Zm'],pars[0]), index=data.index)
data['residuals']=pd.Series(data['magsky']... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
Now that we have a model, we have a way to *predict* the sky brightness. So let's make the same two plots as we did above, but this time plotting the *model* brigthnesses rather than the observed brightnesses. Just to see if we get the same kinds of patterns/behaviours. This next cell is a copy of the earlier one, just... | fig,axes = plt.subplots(1,2, figsize=(15,6))
sc = axes[0].scatter(data['rho'], data['modelsky'], marker='.', c=data['alpha'], cmap='viridis_r')
axes[0].set_xlabel(r'$\rho$', fontsize=16)
axes[0].set_ylabel('Sky brightness (mag/sq-arc-sec)', fontsize=12)
axes[0].text(1.25, 0.5, "lunar phase", va='center', ha='right', ro... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
You will see that there are some patterns that are correctly predicted, but others that are not. In particular, there's a whole cloud of points with $\alpha 22 that are observed but *not* predicted. In other words, we observed some objects where the moon was relatively bright, yet the sky was relatively dark.This is w... | from bokeh.plotting import figure
from bokeh.layouts import gridplot
from bokeh.io import show,output_notebook
from bokeh.models import ColumnDataSource
output_notebook()
source = ColumnDataSource(data)
TOOLS = ['box_select','lasso_select','reset','box_zoom','help']
vars = [('alpha','residuals'),('alpha','rho'),('alph... | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
With a little data exploring, it's pretty obvious that the majority of the outlying points comes from observations when the moon is relatively full but very low (or even below) the horizon. The reason is that the airmass formula that we implemented above has a problem with $Zm > \pi/2$. To see this, we can simply plot ... | from matplotlib.pyplot import plot, xlabel, ylabel,ylim
Z = np.linspace(0, 3*np.pi/4, 100) # make a range of Zenith angles
plot(Z*180/np.pi, X(Z), '-')
xlabel('Zenith angle (degrees)')
ylabel('Airmass') | _____no_output_____ | MIT | MoreNotebooks/Skyfit.ipynb | mahdiqezlou/FlyingCircus |
Visual Data Analysis of Fraudulent Transactions | # initial imports
import pandas as pd
import datetime
import calendar
import plotly.express as px
import matplotlib.pyplot as plt
import hvplot.pandas
from sqlalchemy import create_engine
import psycopg2
%matplotlib inline
# create a connection to the database
engine = create_engine("postgresql://postgres:postgres@loca... | _____no_output_____ | PostgreSQL | visual_data_analysis.ipynb | dbogatic/sql-homework |
Data Analysis Questions 1 Use `hvPlot` to create a line plot showing a time series from the transactions along all the year for **card holders 2 and 18**. In order to contrast the patterns of both card holders, create a line plot containing both lines. What difference do you observe between the consumption patter... | # loading data for card holder 2 and 18 from the database
query = """
SELECT transaction.date, credit_card.id_card_holder, card_holder.name, credit_card.card, transaction.amount, merchant.merchant_name, merchant_category.merchant_category_name
FROM card_holder
LEFT JOIN credit_card
ON credit_card.id_card_holder = car... | _____no_output_____ | PostgreSQL | visual_data_analysis.ipynb | dbogatic/sql-homework |
Conclusions for Question 1 | # Analysis of transactions between 7:00-9:00 for id_2 and id_18 shows that median and mean values are similar, thus it appears no suspicious transactions are occuring. However, it is wise to confirm the validity of small bar transactions (under 2 dol) for Id_18. | _____no_output_____ | PostgreSQL | visual_data_analysis.ipynb | dbogatic/sql-homework |
Data Analysis Question 2 Use `Plotly Express` to create a series of six box plots, one for each month, in order to identify how many outliers could be per month for **card holder id 25**. By observing the consumption patters, do you see any anomalies? Write your own conclusions about your insights. | # loading data of daily transactions from jan to jun 2018 for card holder 25
fraud_detection_df
fraud_detection_df.reset_index(inplace=True)
fraud_detection_df.set_index("id_card_holder", inplace=True)
third_card_holder_df = fraud_detection_df.loc[25]
third_card_holder_df.reset_index(inplace=True)
third_card_holder_df... | _____no_output_____ | PostgreSQL | visual_data_analysis.ipynb | dbogatic/sql-homework |
Conclusions for Question 2 | # Analysis of Id_25 cardholder's transactions show that there were high amount transactions between Jan-June (especially June with 3 high amounts) that took place in pub, bar, restaurant, food truck, suggesting misuse of the corporate credit card.
# identify small transactions less than two dollars
fraud_detection_df ... | _____no_output_____ | PostgreSQL | visual_data_analysis.ipynb | dbogatic/sql-homework |
Comparing and evaluating models | %matplotlib inline
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.notebook_repr_html', True)
import seaborn as sns
sns.set_s... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
The churn exampleThis is a dataset from a telecom company, of their customers. Based on various features of these customers and their calling plans, we want to predict if a customer is likely to leave the company. This is expensive for the company, as a lost customer means lost monthly revenue! | #data set from yhathq: http://blog.yhathq.com/posts/predicting-customer-churn-with-sklearn.html
dfchurn=pd.read_csv("https://dl.dropboxusercontent.com/u/75194/churn.csv")
dfchurn.head() | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Lets write some code to feature select and clean our data first, of-course. | dfchurn["Int'l Plan"] = dfchurn["Int'l Plan"]=='yes'
dfchurn["VMail Plan"] = dfchurn["VMail Plan"]=='yes'
colswewant_cont=[ u'Account Length', u'VMail Message', u'Day Mins', u'Day Calls', u'Day Charge', u'Eve Mins', u'Eve Calls', u'Eve Charge', u'Night Mins', u'Night Calls', u'Night Charge', u'Intl Mins', u'Intl Calls'... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Asymmetry First notice that our data set is very highly asymmetric, with positives, or people who churned, only making up 14-15% of the samples. | ychurn = np.where(dfchurn['Churn?'] == 'True.',1,0)
100*ychurn.mean() | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
This means that a classifier which predicts that EVERY customer is a negative (does not churn) has an accuracy rate of 85-86%. But is accuracy the correct metric? Remember the Confusion matrix? We reproduce it here for convenience - the samples that are +ive and the classifier predicts as +ive are called True Positives... | admin_cost=3
offer_cost=100
clv=1000#customer lifetime value | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
- TN=people we predicted not to churn who wont churn. We associate no cost with this as they continue being our customers- FP=people we predict to churn. Who wont. Lets associate a `admin_cost+offer_cost` cost per customer with this as we will spend some money on getting them not to churn, but we will lose this money.-... | conv=0.5
tnc = 0.
fpc = admin_cost+offer_cost
fnc = clv
tpc = conv*offer_cost + (1. - conv)*(clv+admin_cost)
cost=np.array([[tnc,fpc],[fnc, tpc]])
print cost | [[ 0. 103. ]
[ 1000. 551.5]]
| MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
We can compute the average cost(profit) per person using the following formula, which calculates the "expected value" of the per-customer loss/cost(profit):\begin{eqnarray}Cost &=& c(1P,1A) \times p(1P,1A) + c(1P,0A) \times p(1P,0A) + c(0P,1A) \times p(0P,1A) + c(0P,0A) \times p(0P,0A) \\&=& \frac{TP \times c(1P,1A) + ... | def average_cost(y, ypred, cost):
c=confusion_matrix(y,ypred)
score=np.sum(c*cost)/np.sum(c)
return score | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
No customer churns and we send nothingWe havent made any calculations yet! Lets fix that omission and create our training and test sets. | churntrain, churntest = train_test_split(xrange(dfchurn.shape[0]), train_size=0.6)
churnmask=np.ones(dfchurn.shape[0], dtype='int')
churnmask[churntrain]=1
churnmask[churntest]=0
churnmask = (churnmask==1)
churnmask
testchurners=dfchurn['Churn?'][~churnmask].values=='True.'
testsize = dfchurn[~churnmask].shape[0]
ypred... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Not doing anything costs us 140 per customer. All customers churn, we send everyone | ypred_ste = np.ones(testsize, dtype="int")
print confusion_matrix(testchurners, ypred_ste)
steval=average_cost(testchurners, ypred_ste, cost)
steval | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Make offers to everyone costs us even more, not surprisingly. The first one is the one to beat! Naive Bayes ClassifierSo lets try a classifier. Here we try one known as Gaussian Naive Bayes. We'll just use the default parameters, since the actual details are not of importance to us. | from sklearn.naive_bayes import GaussianNB
clfgnb = GaussianNB()
clfgnb, Xtrain, ytrain, Xtest, ytest=do_classify(clfgnb, None, dfchurn, colswewant_cont+colswewant_cat, 'Churn?', "True.", mask=churnmask)
confusion_matrix(ytest, clfgnb.predict(Xtest))
average_cost(ytest, clfgnb.predict(Xtest), cost) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Ok! We did better! But is this the true value of our cost? To answer this question, we need to ask a question: what exactly is `clf.predict` doing?There is a caveat for SVM's though: we cannot repredict 1's and 0's directly for `clfsvm`, as the SVM is whats called a "discriminative" classifier: it directly gives us a ... | def repredict(est,t, xtest):
probs=est.predict_proba(xtest)
p0 = probs[:,0]
p1 = probs[:,1]
ypred = (p1 >= t)*1
return ypred
average_cost(ytest, repredict(clfgnb, 0.3, Xtest), cost)
plt.hist(clfgnb.predict_proba(Xtest)[:,1]) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Aha! At a 0.3 threshold we save more money!We see that in this situation, where we have asymmetric costs, we do need to change the threshold at which we make our positive and negative predictions. We need to change the threshold so that we much dislike false negatives (same in the cancer case). Thus we must accept many... | from sklearn.metrics import roc_curve, auc
def make_roc(name, clf, ytest, xtest, ax=None, labe=5, proba=True, skip=0):
initial=False
if not ax:
ax=plt.gca()
initial=True
if proba:
fpr, tpr, thresholds=roc_curve(ytest, clf.predict_proba(xtest)[:,1])
else:
fpr, tpr, thresho... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
OK. Now that we have a ROC curve that shows us different thresholds, we need to figure how to pick the appropriate threshold from the ROC curve. But first, let us try another classifier. Classifier Comparison Decision Trees Descision trees are very simple things we are all familiar with. If a problem is multi-dimension... | from sklearn.tree import DecisionTreeClassifier
reuse_split=dict(Xtrain=Xtrain, Xtest=Xtest, ytrain=ytrain, ytest=ytest) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
We train a simple decision tree classifier. | clfdt=DecisionTreeClassifier()
clfdt, Xtrain, ytrain, Xtest, ytest = do_classify(clfdt, {"max_depth": range(1,10,1)}, dfchurn, colswewant_cont+colswewant_cat, 'Churn?', "True.", reuse_split=reuse_split)
confusion_matrix(ytest,clfdt.predict(Xtest)) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Compare! | ax=make_roc("gnb",clfgnb, ytest, Xtest, None, labe=60)
make_roc("dt",clfdt, ytest, Xtest, ax, labe=1) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
How do we read which classifier is better from a ROC curve. The usual advice is to go to the North-West corner of a ROC curve, as that is closest to TPE=1, FPR=0. But thats not our setup here..we have this asymmetric data set. The other advice is to look at the classifier with the highest AUC. But as we can see in the ... | cost
def rat(cost):
return (cost[0,1] - cost[0,0])/(cost[1,0]-cost[1,1])
def c_repredict(est, c, xtest):
r = rat(c)
print r
t=r/(1.+r)
print "t=", t
probs=est.predict_proba(xtest)
p0 = probs[:,0]
p1 = probs[:,1]
ypred = (p1 >= t)*1
return ypred
average_cost(ytest, c_repredict(clf... | 0.229654403567
t= 0.18676337262
| MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
For reasons that will become clearer in a later lab, this value turns out to be only approximate, and we are better using a ROC curve or a Cost curve (below) to find minimum cost. However, it will get us in the right ballpark of the threshold we need. Note that the threshold itself depends only on costs and is independ... | plt.plot(ts, [average_cost(ytest, repredict(clfdt, t, Xtest), cost) for t in ts] ) | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Note that none of this can be done for classifiers that dont provide probabilities. So, once again, we turn to ROC curves to help us out. Model selection from Cost and ROC Notice that the ROC curve has a very interesting property: if you look at the confusion matrix , TPR is only calculated from the observed "1" row wh... | print rat(cost)
slope = rat(cost)*(np.mean(ytest==0)/np.mean(ytest==1))
slope
z1=np.arange(0.,1., 0.02)
def plot_line(ax, intercept):
plt.figure(figsize=(12,12))
ax=plt.gca()
ax.set_xlim([0.0,1.0])
ax.set_ylim([0.0,1.0])
make_roc("gnb",clfgnb, ytest, Xtest, ax, labe=60)
make_roc("dt",clfdt, ytes... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
As you can see our slope is actually on the rising part of the curve, even with the imbalance. (Since the cost ratio isnt too small..an analyst should play around with the assumptions that went into the cost matrix!) Cost curves The proof is always in the pudding. So far we have used a method to calculate a rough thres... | def percentage(tpr, fpr, priorp, priorn):
perc = tpr*priorp + fpr*priorn
return perc
def av_cost2(tpr, fpr, cost, priorp, priorn):
profit = priorp*(cost[1][1]*tpr+cost[1][0]*(1.-tpr))+priorn*(cost[0][0]*(1.-fpr) +cost[0][1]*fpr)
return profit
def plot_cost(name, clf, ytest, xtest, cost, ax=None, thresho... | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
Note the customers on the left of this graph are most likely to churn (be positive).This if you had a finite budget, you should be targeting them!Finding the best classifier has a real consequence: you save money!!! | cost | _____no_output_____ | MIT | Labs/Resources/Misc/Misc1/churn.ipynb | JayParanjape/ml-community |
import os
import json
import shutil
import urllib.request
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Please use the latest version of CmdStanPy
!pip install --upgrade cmdstanpy
# Install pre-built CmdStan binary
# (faster than compiling from source via install_cmdstan() function)
tgz_file ... | _____no_output_____ | Apache-2.0 | Chapter_16_questions.ipynb | cormach/bayesian_stats_by_b_lambert | |
Question 16_1 - discoveries | stan_text = '''data {
int N;
int<lower=0> X[N];
}
parameters {
real<lower=0> mu;
real<lower=0> kappa;
}
model {
X ~ neg_binomial_2(mu, kappa);
mu ~ lognormal(2,1);
kappa ~lognormal(2,1);
}
generated quantities {
int<lower=0> XSim[N];
for (i in 1:N)
{XSim[i] <- neg_binomial_2_rng(mu... | _____no_output_____ | Apache-2.0 | Chapter_16_questions.ipynb | cormach/bayesian_stats_by_b_lambert |
Merge intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.From Leetcode : https://leetcode.com/problems/merge-intervals/ | from operator import itemgetter
def merge_Intervals(intervals):
merged_intervals = []
sorted_intervals = sorted(intervals, key=itemgetter(0))
for i in range(len(sorted_intervals)):
if len(merged_intervals) == 0 or merged_intervals[-1][1] < sorted_intervals[i][0]:
merged_intervals.append(sorted_inter... | _____no_output_____ | Apache-2.0 | Merge Intervals/Merge_Intervals.ipynb | LucasColas/Coding-Problems |
ListsA list is an ordered (not necessarily sorted) sequence of values. | #You create a new list using square brackets
primes = []
print(primes)
type(primes)
#Create a list with some values
primes = [2, 3, 5, 7, 11, 13, 17, 19]
print(primes) | [2, 3, 5, 7, 11, 13, 17, 19]
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
1. Operations | #Concatenate two lists: combine two lists to create a new list
evens = [2, 4, 6, 8]
odds = [1, 3, 5, 7, 9]
numbers = evens + odds
print(numbers)
#Check whether a value is in a list
print(5 in [1, 2, 3, 4, 5])
print(1 in primes)
#Sequence repetition
ripples = [1,2,3] * 3
print(ripples) | [1, 2, 3, 1, 2, 3, 1, 2, 3]
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
2. Built-in function | print("Maximum:", max(primes))
print("Minimum:", min(primes))
print(len(primes), "items")
print("Sum of items", sum(primes))
#But of course, the values of the list must support summation
#This will not work
print(sum(["David", "Celine", "Camille"]))
#If your list is list of boolean values, you can use the any and all
#... | True
True
True
False
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
3. Indexing | #You can access to a particular value of a list via its index
#Note that in Python, the first element has index 0
#Hence the last element has index = len(x) - 1
print(primes[0])
print(primes[1])
print(primes[3])
#Negative indices allow you to go from the end of the list
print(primes[-1])
print(primes[-2])
print(primes... | True
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
4. Slicing | #Recall the previous list of prime numbers
primes = [2, 3, 5, 7, 11, 13, 17, 19]
#Slicing allows you to take a slice - or a chop - of the list
#and return a new list containing the elements of your slice
#The second value of your slice is excluded
#From the first (index 0) to the fourth (index 3) value
x = primes[0:4... | [19, 17, 13, 11, 7, 5, 3, 2]
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
4. Methods | #append to the end of the list
primes.append(23)
print(primes)
primes.append(25)
print(primes)
#remove the first instance of a given value
primes.remove(25)
print(primes)
#if the value doesnt exist... you get an error!
primes.remove(99)
print(primes)
#delete a value at a position, and save it
deleted = primes.pop(1) #t... | [2, 3, 5, 7, 11, 13, 17, 19, 23, 23]
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
5. Iteration | i = 0
while i < len(primes):
print("{} is a prime number".format(primes[i]))
i += 1
#More pythonic way: use this syntax!
for value in primes:
print("{} is still a prime number".format(value)) | 2 is still a prime number
3 is still a prime number
5 is still a prime number
7 is still a prime number
11 is still a prime number
13 is still a prime number
17 is still a prime number
19 is still a prime number
23 is still a prime number
23 is still a prime number
| MIT | 08 - Lists.ipynb | dschenck/Python-crash-course |
Parasite axis demoThis example demonstrates the use of parasite axis to plot multiple datasetsonto one single plot.Notice how in this example, *par1* and *par2* are both obtained by calling``twinx()``, which ties their x-limits with the host's x-axis. From there, eachof those two axis behave separately from each other... | from mpl_toolkits.axes_grid1 import host_subplot
from mpl_toolkits import axisartist
import matplotlib.pyplot as plt
host = host_subplot(111, axes_class=axisartist.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
par2.axis["right"] = par2.new_fixed_axis(loc="right", offset=(60, 0))
par1... | _____no_output_____ | MIT | scr/.ipynb_checkpoints/demo_parasite_axes2-checkpoint.ipynb | RivasCalduch/IndiceReferenciaMercadoHipotecario_Visualizacion |
Neuromatch Academy: Week 1, Day 2, Tutorial 2 Modeling Practice: Model implementation and evaluation__Content creators:__ Marius 't Hart, Paul Schrater, Gunnar Blohm__Content reviewers:__ Norma Kuhn, Saeed Salehi, Madineh Sarvestani, Spiros Chavlis, Michael Waskom --- Tutorial objectivesWe are investigating a simple ... | import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.stats import gamma
from IPython.display import YouTubeVideo
# @title Figure settings
import ipywidgets as widgets
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/cour... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
--- Section 6: Model planning | # @title Video 6: Planning
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "//player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, ... | Video available at https://youtube.com/watch?v=dRTOFFigxa0
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Goal:** Identify the key components of the model and how they work together.Our goal all along has been to model our perceptual estimates of sensory data.Now that we have some idea of what we want to do, we need to line up the components of the model: what are the input and output? Which computations are done and in ... | def my_train_illusion_model(sensorydata, params):
"""
Generate output predictions of perceived self-motion and perceived
world-motion velocity based on input visual and vestibular signals.
Args:
sensorydata: (dict) dictionary with two named entries:
opticflow: (numpy.ndarray of float) NxM array wi... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
We've also completed the `my_perceived_motion()` function for you below. Follow this example to complete the template for `my_selfmotion()` and `my_worldmotion()`. Write out the inputs and outputs, and the steps required to calculate the outputs from the inputs.**Perceived motion function** | # Full perceived motion function
def my_perceived_motion(vis, ves, params):
"""
Takes sensory data and parameters and returns predicted percepts
Args:
vis (numpy.ndarray) : 1xM array of optic flow velocity data
ves (numpy.ndarray) : 1xM array of vestibular acceleration data
params ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
TD 6.1: Formulate purpose of the self motion functionNow we plan out the purpose of one of the remaining functions. **Only name input arguments, write help text and comments, _no code_.** The goal of this exercise is to make writing the code (in Micro-tutorial 7) much easier. Based on our work before the break, you sh... | def my_selfmotion(arg1, arg2):
"""
Short description of the function
Args:
argument 1: explain the format and content of the first argument
argument 2: explain the format and content of the second argument
Returns:
what output does the function generate?
Any further descri... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_90e4d753.py) **Template calculate world motion**We have drafted the help text and written comments in the function below that describe the inputs, the outputs, and op... | # World motion function
def my_worldmotion(vis, selfmotion, params):
"""
Estimates world motion based on the visual signal, the estimate of
Args:
vis (numpy.ndarray): 1xM array with the optic flow signal
selfmotion (float): estimate of self motion
params (dict): dictionary with na... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
--- Section 7: Model implementation | # @title Video 7: Implementation
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "//player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, he... | Video available at https://youtube.com/watch?v=DMSIt7t-LO8
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Goal:** We write the components of the model in actual code.For the operations we picked, there function ready to use:* integration: `np.cumsum(data, axis=1)` (axis=1: per trial and over samples)* filtering: `my_moving_window(data, window)` (window: int, default 3)* take last `selfmotion` value as our estimate* thres... | # Self motion function
def my_selfmotion(ves, params):
"""
Estimates self motion for one vestibular signal
Args:
ves (numpy.ndarray): 1xM array with a vestibular signal
params (dict) : dictionary with named entries:
see my_train_illusion_model() for detai... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_53312239.py) Interactive Demo: Unit testingTesting if the functions you wrote do what they are supposed to do is important, and known as 'unit testing'. Here we will... | #@title
#@markdown Make sure you execute this cell to enable the widget!
def refresh(threshold=0, windowsize=100):
params = {'samplingrate': 10, 'FUN': np.mean}
params['filterwindows'] = [windowsize, 50]
params['threshold'] = threshold
selfmotion_estimates = np.empty(200)
# get the estimates fo... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Estimate world motion**We have completed the `my_worldmotion()` function for you below. | # World motion function
def my_worldmotion(vis, selfmotion, params):
"""
Short description of the function
Args:
vis (numpy.ndarray): 1xM array with the optic flow signal
selfmotion (float): estimate of self motion
params (dict): dictionary with named entries:
see my_tra... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
--- Section 8: Model completion | # @title Video 8: Completion
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "//player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height... | Video available at https://youtube.com/watch?v=EM-G8YYdrDg
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Goal:** Make sure the model can speak to the hypothesis. Eliminate all the parameters that do not speak to the hypothesis.Now that we have a working model, we can keep improving it, but at some point we need to decide that it is finished. Once we have a model that displays the properties of a system we are interested... | # @markdown Run to plot model predictions of motion estimates
# prepare to run the model again:
data = {'opticflow': opticflow, 'vestibular': vestibular}
params = {'threshold': 0.6, 'filterwindows': [100, 50], 'FUN': np.mean}
modelpredictions = my_train_illusion_model(sensorydata=data, params=params)
# process the dat... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Questions:*** How does the distribution of data points compare to the plot in TD 1.2 or in TD 7.1?* Did you expect to see this?* Where do the model's predicted judgments for each of the two conditions fall?* How does this compare to the behavioral data?However, the main observation should be that **there are illusion... | # @title Video 9: Evaluation
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "//player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height... | Video available at https://youtube.com/watch?v=bWLFyobm4Rk
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
**Goal:** Once we have finished the model, we need a description of how good it is. The question and goals we set in micro-tutorial 1 and 4 help here. There are multiple ways to evaluate a model. Aside from the obvious fact that we want to get insight into the phenomenon that is not directly accessible without the mode... | # @markdown Run to plot predictions over data
my_plot_predictions_data(judgments, predictions) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
When model predictions are correct, the red points in the figure above should lie along the identity line (a dotted black line here). Points off the identity line represent model prediction errors. While in each plot we see two clusters of dots that are fairly close to the identity line, there are also two clusters tha... | # @markdown Run to calculate R^2
conditions = np.concatenate((np.abs(judgments[:, 1]), np.abs(judgments[:, 2])))
veljudgmnt = np.concatenate((judgments[:, 3], judgments[:, 4]))
velpredict = np.concatenate((predictions[:, 3], predictions[:, 4]))
slope, intercept, r_value,\
p_value, std_err = stats.linregress(conditio... | conditions -> judgments R^2: 0.032
predictions -> judgments R^2: 0.256
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
These $R^2$s express how well the experimental conditions explain the participants judgments and how well the models predicted judgments explain the participants judgments.You will learn much more about model fitting, quantitative model evaluation and model comparison tomorrow!Perhaps the $R^2$ values don't seem very i... | #@title
#@markdown Make sure you execute this cell to enable the widget!
data = {'opticflow': opticflow, 'vestibular': vestibular}
def refresh(threshold=0, windowsize=100):
# set parameters according to sliders:
params = {'samplingrate': 10, 'FUN': np.mean}
params['filterwindows'] = [windowsize, 50]
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
Varying the parameters this way, allows you to increase the models' performance in predicting the actual data as measured by $R^2$. This is called model fitting, and will be done better in the coming weeks. TD 9.2: Credit assigmnent of self motionWhen we look at the figure in **TD 8.1**, we can see a cluster does seem... | def my_selfmotion(ves, params):
"""
Estimates self motion for one vestibular signal
Args:
ves (numpy.ndarray): 1xM array with a vestibular signal
params (dict): dictionary with named entries:
see my_train_illusion_model() for details
Returns:
(float): an estimate of... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_51dce10c.py)*Example output:* That looks much better, and closer to the actual data. Let's see if the $R^2$ values have improved. Use the optimal values for the thres... | #@title
#@markdown Make sure you execute this cell to enable the widget!
data = {'opticflow': opticflow, 'vestibular': vestibular}
def refresh(threshold=0, windowsize=100):
# set parameters according to sliders:
params = {'samplingrate': 10, 'FUN': np.mean}
params['filterwindows'] = [windowsize, 50]
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
While the model still predicts velocity judgments better than the conditions (i.e. the model predicts illusions in somewhat similar cases), the $R^2$ values are a little worse than those of the simpler model. What's really going on is that the same set of points that were model prediction errors in the previous model a... | # @title Video 10: Publication
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "//player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, heig... | Video available at https://youtube.com/watch?v=zm8x7oegN6Q
| CC-BY-4.0 | tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb | Jaycob-jh/course-content |
Exercise 6, answers Problem 1 | from pyomo.environ import *
model = ConcreteModel()
#Three variables
model.x = Var([1,2,3])
#Objective function including powers and logarithm
model.OBJ = Objective(expr = log(model.x[1]**2+1)+model.x[2]**4
+model.x[1]*model.x[3]) #Objective function
model.constr = Constraint(expr = model.x[1]**3... |
******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
Ipopt is released as open source code under the Eclipse Public License (EPL).
For more information visit http://projects.coin-or.org/Ipopt
***********... | CC-BY-3.0 | Exercise 6, answers.ipynb | maeehart/TIES483 |
Problem 2 The set Pareto optimal solutions is $\{(t,1-t):t\in[0,1]\}$.Let us denote set of Pareto optimal solutions by $PS$ and show that $PS=\{(t,1-t):t\in[0,1]\}$.$PS\supset\{(t,1-t):t\in[0,1]\}$:Let's assume that there exists $t\in[0,1]$, which is not Pareto optimal. Then there exists $x=(x_1,x_2)\in\mathbb R^2$ an... | def prob(x):
return [(x[0]-1)**2+x[1]**2,x[0]**2+(x[1]-1)**2] | _____no_output_____ | CC-BY-3.0 | Exercise 6, answers.ipynb | maeehart/TIES483 |
Let's do this using Pyomo: | from pyomo.environ import *
from pyomo.opt import SolverFactory #Import interfaces to solvers
def weighting_method_pyomo(f,w):
points = []
for wi in w:
model = ConcreteModel()
model.x = Var([0,1])
#weighted sum
model.obj = Objective(expr = wi[0]*f(model.x)[0]+wi[1]*f(model.x)[1]... | _____no_output_____ | CC-BY-3.0 | Exercise 6, answers.ipynb | maeehart/TIES483 |
**Plot the solutions in the objective space** | import matplotlib.pyplot as plt
f_repr_ws = [prob(repri) for repri in repr]
fig = plt.figure()
plt.scatter([z[0] for z in f_repr_ws],[z[1] for z in f_repr_ws])
plt.show() | _____no_output_____ | CC-BY-3.0 | Exercise 6, answers.ipynb | maeehart/TIES483 |
**Plot the solutions in the decision space** | import matplotlib.pyplot as plt
fig = plt.figure()
plt.scatter([x[0] for x in repr],[x[1] for x in repr])
plt.show() | _____no_output_____ | CC-BY-3.0 | Exercise 6, answers.ipynb | maeehart/TIES483 |
Bonus: Temperature Analysis I | import pandas as pd
from datetime import datetime as dt
# "tobs" is "temperature observations"
df = pd.read_csv('Resources/hawaii_measurements.csv')
df.head()
# Convert the date column format from string to datetime
df["date"] = pd.to_datetime(df['date'])
df.info()
# Set the date column as the DataFrame index
# Drop th... | _____no_output_____ | ADSL | temp_analysis_bonus_1_starter.ipynb | georgiafbi/sqlalchemy-challenge |
Compare June and December data across all years | import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import scipy.stats as stats
from scipy.stats import ttest_rel
# Filter data for desired months
june_df = df[df.index.month==6]
dec_df=df[df.index.month==12]
# Identify the average temperature for... | _____no_output_____ | ADSL | temp_analysis_bonus_1_starter.ipynb | georgiafbi/sqlalchemy-challenge |
Open-EDI Python Demo ----- Hello World import openediIf failed, check whether the python version for jupyter-notebook and that for building the project are consistent | import sys
module_dir = ["../lib/", "./lib/", "../build/edi/python/"] # find from install_dir or build_dir
sys.path.extend(module_dir)
import openedi as edi
edi.ediPrint(edi.MessageType.kInfo, "Hello World.\n") | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
创建一个database | db = edi.db.Database() | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
创建一个model, 并添加相应model term | m0 = db.addModel("model0")
m0.setModelType(edi.ModelType.kCell)
mt0 = m0.addTerm("term0")
mt0.setSignalDirect(edi.SignalDirection.kInput)
mt1= m0.addTerm("term1")
mt1.setSignalDirect(edi.SignalDirection.kOutput) | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
创建一个design | design = db.getDesign() | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
在design里创建两个instances | inst0 = design.addInst()
inst0.getAttr().setName("inst0")
p0 = edi.geo.Point2DInt(0, 1)
inst0.getAttr().setLoc(p0)
inst0.addModel(m0)
attr1 = edi.db.InstAttr()
attr1.setName("inst1")
p1 = edi.geo.Point2DInt(2, 3)
attr1.setLoc(p1)
inst1 = design.addInst(attr1)
inst1.addModel(m0) | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
创建相应instance terms, 并连接至一个net | net0 = design.addNet()
net0.getAttr().setName("net0")
inst_term0 = design.addInstTerm()
inst_term0.getAttr().setModelTerm(mt0)
inst_term0.setInst(inst0)
inst_term0.setNet(net0)
inst0.addInstTerm(inst_term0)
net0.addInstTerm(inst_term0)
inst_term1 = design.addInstTerm()
inst_term1.getAttr().setModelTerm(mt1)
inst_term... | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
将database写入文件 | filename = "demo_db.txt"
edi.db.write(db, filename, 0) # 0 means ascii mode, 1 means binary mode | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
从文件读入database | db2 = edi.db.Database()
edi.db.read(db2, filename, 0) # 0 means ascii mode, 1 means binary mode
print("We have %d models in db2." % (db2.numModels())) # =1
print("We have %d insts in db2.design_." % (db2.getDesign().numInsts())) # =2
print("We have %d nets in db2.design_." % (db2.getDesign().numNets())) # =1
print("We ... | _____no_output_____ | BSD-3-Clause | demo/hello-world.ipynb | lbz007/rectanglequery |
Load datasets, split, normalize etc.. | datasets = np.load("datasets.npy")
labels = np.load("labels.npy")
datasets_val = np.load("datasets_val.npy")
labels_val = np.load("labels_val.npy")
datasets.shape
X_train,X_test,y_train, y_test = train_test_split(datasets, labels, test_size=0.05,random_state=4242)
# min-max normalization (can try other also..)
def no... | min:-1.547 max:74.888 mean:-0.000 std:1.000
min:-1.376 max:62.494 mean:0.000 std:1.000
min:-1.411 max:49.713 mean:-0.000 std:1.000
| MIT | train_test_nnets.ipynb | cemysf/BCI |
- Make channel the last axis | X_train = np.swapaxes(X_train, -2, -1)
X_test = np.swapaxes(X_test, -2, -1)
X_val = np.swapaxes(X_val, -2, -1)
X_test.shape | _____no_output_____ | MIT | train_test_nnets.ipynb | cemysf/BCI |
- Labels to one hot | def to_numericalLabel(x):
if x == "left":
return 0
elif x == "none":
return 1
elif x == "right":
return 2
y_train = [to_numericalLabel(l) for l in y_train]
y_test = [to_numericalLabel(l) for l in y_test]
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_train[:10]
... | _____no_output_____ | MIT | train_test_nnets.ipynb | cemysf/BCI |
Try 1: simple conv net - 2D conv and max poolings, with skip connections (add)- Dense at the end for classification | input_img = Input(shape=(250,60,16)) ## 16 channels
learning_rate = 5e-4 ## 1e-3 is default for adam
reg_param = 1e-2
def net_model(input_img):
conv1 = Convolution2D(32, (3,3), activation="Mish", padding="same", kernel_regularizer=l2(reg_param))(input_img)
# add1
pool1 = MaxPooling2D((2,2), padding="sa... | Train on 999 samples, validate on 53 samples
Epoch 1/50
999/999 [==============================] - 17s 17ms/step - loss: 3.1340 - accuracy: 0.3534 - val_loss: 2.5861 - val_accuracy: 0.4340
Epoch 2/50
999/999 [==============================] - 17s 17ms/step - loss: 2.4655 - accuracy: 0.4875 - val_loss: 2.5292 - val_accu... | MIT | train_test_nnets.ipynb | cemysf/BCI |
Check results | ### https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the c... | accuracy:0.4894 f1:0.4805
| MIT | train_test_nnets.ipynb | cemysf/BCI |
 基于深度学习的图像检索 \[稀牛学院 x 网易云课程\]《深度学习工程师(实战)》课程资料 by [@寒小阳](https://blog.csdn.net/han_xiaoyang)**提示:如果大家觉得计算资源有限,欢迎大家在翻-墙后免费试用[google的colab](https://colab.research.google.com),有免费的K80 GPU供大家使用,大家只需要把课程的notebook上传即可运行** | !rm -rf tiny* features
!wget http://cs231n.stanford.edu/tiny-imagenet-200.zip
import zipfile
zfile = zipfile.ZipFile('tiny-imagenet-200.zip','r')
zfile.extractall()
zfile.close()
!ls
!ls tiny-imagenet-200
!ls tiny-imagenet-200/train/n01443537/images | wc -l
# -*- coding: utf-8 -*-
import os
import random
# 打开文件以便写入图片名... | tiny-imagenet-200/train/n02843684/images/n02843684_219.JPEG
tiny-imagenet-200/train/n02843684/images/n02843684_66.JPEG
tiny-imagenet-200/train/n02843684/images/n02843684_152.JPEG
tiny-imagenet-200/train/n02843684/images/n02843684_479.JPEG
tiny-imagenet-200/train/n02843684/images/n02843684_95.JPEG
| Apache-2.0 | 2.cnn_based_image_retrievel.ipynb | DowsonLewis/MachineLearning-work |
图像特征抽取 \[稀牛学院 x 网易云课程\]《深度学习工程师(实战)》课程资料 by [@寒小阳](https://blog.csdn.net/han_xiaoyang) | import numpy as np
from numpy import linalg as LA
import h5py
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
import keras.applications.inception_v3 as inception_v3
import keras.applications.vgg16 as vgg16
from keras.applications.vgg16 import VGG16
class InceptionNet:
... | Using TensorFlow backend.
| Apache-2.0 | 2.cnn_based_image_retrievel.ipynb | DowsonLewis/MachineLearning-work |
遍历图片抽取图像特征并存储 \[稀牛学院 x 网易云课程\]《深度学习工程师(实战)》课程资料 by [@寒小阳](https://blog.csdn.net/han_xiaoyang) | print("--------------------------------------------------")
print(" 特征抽取开始 ")
print("--------------------------------------------------")
# 特征与文件名存储列表
feats = []
names = []
# 读取图片列表
img_list = open("ImageName.txt", 'r').readlines()
img_list = [image.strip() for image in img_list]... | _____no_output_____ | Apache-2.0 | 2.cnn_based_image_retrievel.ipynb | DowsonLewis/MachineLearning-work |
使用近似最近邻算法加速 \[稀牛学院 x 网易云课程\]《深度学习工程师(实战)》课程资料 by [@寒小阳](https://blog.csdn.net/han_xiaoyang) | feats.shape
!pip install nearpy
from nearpy import Engine
from nearpy.hashes import RandomBinaryProjections
DIMENSIONS = 512
PROJECTIONBITS = 16
ENGINE = Engine(DIMENSIONS, lshashes=[RandomBinaryProjections('rbp', PROJECTIONBITS,rand_seed=2611),
RandomBinaryProjections('rbp', PROJ... | _____no_output_____ | Apache-2.0 | 2.cnn_based_image_retrievel.ipynb | DowsonLewis/MachineLearning-work |
Linear Regression for North American Pumpkins - Lesson 1 Import needed libraries | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, model_selection
| _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Load the diabetes dataset, divided into `X` data and `y` features | X, y = datasets.load_diabetes(return_X_y=True)
print(X.shape)
print(X[0]) | (442, 10)
[ 0.03807591 0.05068012 0.06169621 0.02187235 -0.0442235 -0.03482076
-0.04340085 -0.00259226 0.01990842 -0.01764613]
| MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Select just one feature to target for this exercise | X = X[:, np.newaxis, 2]
| _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Split the training and test data for both `X` and `y` | X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
| _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Select the model and fit it with the training data | model = linear_model.LinearRegression()
model.fit(X_train, y_train) | _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Use test data to predict a line | y_pred = model.predict(X_test)
| _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Display the results in a plot | plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show() | _____no_output_____ | MIT | 2-Regression/1-Tools/solution/notebook.ipynb | buseorak/ML-For-Beginners |
Flow Cytometry DataLoad AML data from 21 samples, 5 of them are healthy (H\*), 16 of them are AML samples (SJ\*). | %%time
# load data into a dictionary of pandas data frames
PATH_DATA = '/extra/disij0/data/flow_cytometry/cytobank/levine_aml/CSV/'
#PATH = '/Users/disiji/Dropbox/current/flow_cytometry/acdc/data/'
user_ids = ['H1','H2','H3','H4','H5','SJ01','SJ02','SJ03','SJ04','SJ05','SJ06','SJ07','SJ08','SJ09','SJ10',\
... | ['HLA-DR', 'CD19', 'CD34', 'CD45', 'CD47', 'CD44', 'CD117', 'CD123', 'CD38', 'CD11b', 'CD7', 'CD15', 'CD3', 'CD64', 'CD33', 'CD41']
(14, 16)
HLA-DR CD19 CD34 CD45 CD47 CD44 CD117 CD123 \
Basophils -1.0 -1 -1 0.0 0.0 0.0 0.0 1
CD4 T cells ... | MIT | small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb | disiji/fc_mondrian |
Now run MCMC to collect posterior samples... Random effect model Training models for healthy samples | f = lambda x: np.arcsinh((x -1.)/5.)
data = [data_dict[_].head(20000).applymap(f)[markers].values for _ in ['H1','H2','H3','H4','H5']]
# compute data range
data_ranges = np.array([[[data[_][:,d].min(),data[_][:,d].max()] \
for d in range(len(markers))]
for _ in range(le... | _____no_output_____ | MIT | small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb | disiji/fc_mondrian |
Training models for unhealthy samples | data = [data_dict[_].head(20000).applymap(f)[markers].values for _ in ['SJ01','SJ02',\
'SJ03','SJ04','SJ05','SJ06','SJ07','SJ08','SJ09','SJ10',\
'SJ11','SJ12','SJ13','SJ14','SJ15','SJ16']]
# compute data range
data_ranges = np.array([[[data[_][:,d].min(),data[_][:,d].max()] \
... | _____no_output_____ | MIT | small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb | disiji/fc_mondrian |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.