markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We define the source to be scanned from the lineAll.db | def outputMatch(matches, minmatch = 5, mainLines = None):
for m in matches:
imax = len(m)
ifound = 0
redshift = m[0]
for i in range(1,len(m)):
if len(m[i]) > 0:
ifound += 1
if mainLines != None:
ifoun... | notebooks/lines/scanningLineRedshiftwithSplat.ipynb | bosscha/alma-calibrator | gpl-2.0 |
Scan through the lines (lineid) matching with a local splatalogue.db. emax is the maximum energy of the upper level to restrain to low energy transitions... | m = al.scanningSplatRedshiftSourceLineid(lineid, zmin = redshift , zmax = 0.90, dz = 1e-4,nrao = True, emax= 40., absorption = True, emission = True )
redshift = []
lineDetected =[]
minmatch = 15
for l in m:
redshift.append(l[0])
ifound = 0
for i in range(1,len(l)):
if len(l[i]) > 0:
... | notebooks/lines/scanningLineRedshiftwithSplat.ipynb | bosscha/alma-calibrator | gpl-2.0 |
Plot the detected lines vs. the redshift. | pl.figure(figsize=(15,10))
pl.xlabel("z")
pl.ylabel("Lines")
pl.plot(redshift, lineDetected, "k-")
pl.show()
## uncomment to save data in a pickle file
f = open("3c273-redshift-hires-scan.pickle","w")
pickle.dump(m,f )
f.close()
| notebooks/lines/scanningLineRedshiftwithSplat.ipynb | bosscha/alma-calibrator | gpl-2.0 |
Display the matching transitions | mL = ['CO v=0','HCN','HCO+']
outputMatch(m, minmatch=3, mainLines = None) | notebooks/lines/scanningLineRedshiftwithSplat.ipynb | bosscha/alma-calibrator | gpl-2.0 |
Hack for Heat #3: Number of complaints over time
This time, we're going to look at raw 311 complaint data. The data that I was working with previously was summarized data.
This dataset is much bigger, which is nice because it'll give me a chance to maintain my SQL-querying-from-memory-skills.
First, we're going to have... | connection = psycopg2.connect('dbname = threeoneone user=threeoneoneadmin password=threeoneoneadmin')
cursor = connection.cursor() | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
For example, we might want to extract the column names from our table: | cursor.execute('''SELECT * FROM threeoneone.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'service'; ''')
columns = cursor.fetchall()
columns = [x[3] for x in columns]
columns[0:5] | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Complaints over time
Let's start with something simple. First, let's extract a list of all complaints, and the plot the number of complaints by month. | cursor.execute('''SELECT createddate FROM service;''')
complaintdates = cursor.fetchall()
complaintdates = pd.DataFrame(complaintdates)
complaintdates.head() | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Renaming our column: | complaintdates.columns = ['Date'] | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Next we have to convert these tuples into strings: | complaintdates['Date'] = [x [0] for x in complaintdates['Date']] | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Normally, if these were strings, we'd use the extract_dates function we wrote in a previous post. However, because I typed these as datetime objects, we can just extract the .year(), .month(), and .day() attributes: | type(complaintdates['Date'][0])
complaintdates['Day'] = [x.day for x in complaintdates['Date']]
complaintdates['Month'] = [x.month for x in complaintdates['Date']]
complaintdates['Year'] = [x.year for x in complaintdates['Date']] | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
This is how many total complaints we have: | len(complaintdates) | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
We can group them by month: | bymonth = complaintdates.groupby(by='Month').count()
bymonth | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
By year: | byyear = complaintdates.groupby(by='Year').count()
byyear
byday = complaintdates.groupby(by='Day').count()
bydate = complaintdates.groupby(by='Date').count() | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Some matplotlib | plt.figure(figsize = (12,10))
x = range(0,12)
y = bymonth['Date']
plt.plot(x,y)
plt.figure(figsize = (12,10))
x = range(0,7)
y = byyear['Date']
plt.plot(x,y)
plt.figure(figsize = (12,10))
x = range(0,len(byday))
y = byday['Date']
plt.plot(x,y) | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
The sharp decline we see at the end is obviously because not all months have the same number of days. | plt.figure(figsize=(12,10))
x = range(0,len(bydate))
y = bydate['Year'] #This is arbitrary - year, month, and day are all series that store the counts
plt.plot(x,y) | src/bryan analyses/Hack for Heat #3.ipynb | heatseeknyc/data-science | mit |
Load and Process the data | text = open('data/holmes.txt').read().lower()
print('Total characters: {}'.format(len(text)))
text[:300] | text_generator.ipynb | angelmtenor/data-science-keras | mit |
Preprocess the data | text = text[1302:] # remove title, author page, and table of contents
text = text.replace('\n', ' ')
text = text.replace('\r', ' ')
unique_characters = set(list(text))
print(unique_characters)
# remove non-english characters
import re
text = re.sub("[$%&'()*@/àâèé0123456789-]", " ", text)
text = text.replace('"', ' ... | text_generator.ipynb | angelmtenor/data-science-keras | mit |
Split data into input/output pairs | # Transforms the input text and window-size into a set of input/output pairs
# for use with the RNN """
window_size = 100
step_size = 5
input_pairs = []
output_pairs = []
for i in range(0, len(text) - window_size, step_size):
input_pairs.append(text[i:i + window_size])
output_pairs.append(text[i + window_si... | text_generator.ipynb | angelmtenor/data-science-keras | mit |
One-hot encoding characters | chars_to_indices = dict((c, i) for i, c in enumerate(chars))
indices_to_chars = dict((i, c) for i, c in enumerate(chars))
# create variables for one-hot encoded input/output
X = np.zeros((len(input_pairs), window_size, num_chars), dtype=np.bool)
y = np.zeros((len(input_pairs), num_chars), dtype=np.bool)
# transform c... | text_generator.ipynb | angelmtenor/data-science-keras | mit |
Recurrent Neural Network Model | from keras.models import Sequential
from keras.layers import Dense, Activation, LSTM
model = Sequential()
model.add(LSTM(200, input_shape=(window_size, num_chars)))
model.add(Dense(num_chars, activation=None))
model.add(Dense(num_chars, activation="softmax"))
model.summary()
optimizer = keras.optimizers.RMSprop(lr=0.... | text_generator.ipynb | angelmtenor/data-science-keras | mit |
Make predictions | model = keras.models.load_model(model_path)
print("Model loaded:", model_path)
def predict_next_chars(model, input_chars, num_to_predict):
""" predict a number of future characters """
predicted_chars = ''
for i in range(num_to_predict):
x_test = np.zeros((1, window_size, len(chars)))
for... | text_generator.ipynb | angelmtenor/data-science-keras | mit |
Streaming with tweepy
The Twitter streaming API is used to download twitter messages in real time. We use streaming api instead of rest api because, the REST api is used to pull data from twitter but the streaming api pushes messages to a persistent session. This allows the streaming api to download more data in real t... | # Tweet listner class which subclasses from tweepy.StreamListener
class TweetListner(tweepy.StreamListener):
"""Twitter stream listner"""
def __init__(self, csocket):
self.clientSocket = csocket
def dataProcessing(self, data):
"""Process the data, before sending to spark stream... | TweetAnalysis/Final/Q1/Dalon_4_RTD_MiniPro_Tweepy_Q1.ipynb | dalonlobo/GL-Mini-Projects | mit |
Drawbacks of twitter streaming API
The major drawback of the Streaming API is that Twitter’s Steaming API provides only a sample of tweets that are occurring. The actual percentage of total tweets users receive with Twitter’s Streaming API varies heavily based on the criteria users request and the current traffic. Stud... | def getWOEIDForTrendsAvailable(api, place):
"""Returns the WOEID of the country if the trend is available there. """
# Iterate through trends
data = api.trends_available()
for item in data:
if item["name"] == place: # Use place = "Worldwide" to get woeid of world
woeid = item["... | TweetAnalysis/Final/Q1/Dalon_4_RTD_MiniPro_Tweepy_Q1.ipynb | dalonlobo/GL-Mini-Projects | mit |
JSON file beolvasás | pd.read_json('data.json') | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
Excel file beolvasás: sorok kihagyhatók a file tetejéről, munkalap neve választható. | df=pd.read_excel('2.17deaths causes.xls',sheet_name='2.17',skiprows=5) | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
numpy egy matematikai bővítőcsomag | import numpy as np | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
A nan értékek numpy-ban vannak definiálva. | df=df.set_index('Unnamed: 0').dropna(how='any').replace('-',np.nan)
df2=pd.read_excel('2.17deaths causes.xls',sheet_name='2.17',skiprows=4) | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
ffill azt jelenti forward fill, és a nan-okat kitölti a balra vagy fölötte álló értékkel. Az axis=0 a sorokat jelenti, az axis=1 az oszlopokat. | df2.loc[[0]].ffill(axis=1) | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
Sorok/oszlopok törlése. | df=df.drop('Unnamed: 13',axis=1)
df.columns
[year for year in range(2011,2017)]
df.columns=[year for year in range(2011,2017) for k in range(2)] | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
Nested pythonic lista - két felsorolás egymás után | [str(year)+'-'+str(k) for year in range(2011,2017) for k in range(2)]
nemek=['Masculin','Feminin']
[str(year)+'-'+nem for year in range(2011,2017) for nem in nemek]
df.columns=[str(year)+'-'+nem for year in range(2011,2017) for nem in nemek]
df
evek=[str(year) for year in range(2011,2017) for nem in nemek]
nemlista=... | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
Új oszlopok a dimenzióknak. | df['Ev']=evek
df['Nem']=nemlista
df.head(6)
df.set_index(['Ev','Nem']) | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
unstack paranccsal egy MultiIndex (azaz többszintes index) pivot-álható. | df.set_index(['Ev','Nem'])[['Total']].unstack() | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
Hiányzó értékek (nan-ok) helyettesítése. | pd.DataFrame([0,3,4,5,'gfgf',np.nan]).replace(np.nan,'Mas')
pd.DataFrame([0,3,4,5,'gfgf',np.nan]).fillna('Mas') | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
join - több DataFrame összefűzése. Az index ugyanaz kell legyen. Az oszlopok nevei különbözőek. Az index neve nem számít. | df1=pd.read_excel('pensiunea comfort 1.xlsx',sheet_name='Sheet1')
df2=pd.read_excel('pensiunea comfort 1.xlsx',sheet_name='Sheet2')
df3=pd.read_excel('pensiunea comfort 1.xlsx',sheet_name='Sheet3')
df1=df1.dropna(how='all',axis=0).dropna(how='all',axis=1).set_index(2019)
df2=df2.dropna(how='all',axis=0).dropna(how='al... | present/bi/2020/jupyter/2_pandas_filetipusok.ipynb | csaladenes/csaladenes.github.io | mit |
SVD is one of the matrix factorization tecniques. It factors a matrix into three parts with which we can reconstruct the initial matrix. However, reconstructing original matrix is not mostly the primary aim. Rather, we factorize matrices in order to achive following goals:
to find principal components
to reduce matrix... | A = np.mat([
[4, 5, 4, 1, 1],
[5, 3, 5, 0, 0],
[0, 1, 0, 1, 1],
[0, 0, 0, 0, 1],
[1, 0, 0, 4, 5],
[0, 1, 0, 5, 4],
])
U, S, V = np.linalg.svd(A)
U.shape, S.shape, V.shape | SingularValueDecomposition.ipynb | muatik/dm | mit |
Left singular vectors | U | SingularValueDecomposition.ipynb | muatik/dm | mit |
Singular values | S
np.diag(S) | SingularValueDecomposition.ipynb | muatik/dm | mit |
As you can see, the singular values are sorted descendingly.
Right singular values | V | SingularValueDecomposition.ipynb | muatik/dm | mit |
Reconstructing the original matrix | def reconstruct(U, S, V, rank):
return U[:,0:rank] * np.diag(S[:rank]) * V[:rank]
r = len(S)
reconstruct(U, S, V, r) | SingularValueDecomposition.ipynb | muatik/dm | mit |
We use all the dimentions to get back to the original matrix. As a result, we obtain the matrix which is almost identical. Let's calculate the difference between the two matrices. | def calcError(A, B):
return np.sum(np.power(A - B, 2))
calcError(A, reconstruct(U, S, V, r)) | SingularValueDecomposition.ipynb | muatik/dm | mit |
Expectedly, the error is infinitesimal.
However, most of the time this is not our intention. Instead of using all the dimentions(rank), we only use some of them, which have more variance, in other words, which provides more information. Let's see what we will get when using only the first three most significant dimenti... | reconstruct(U, S, V, 3)
calcError(A, reconstruct(U, S, V, 3)) | SingularValueDecomposition.ipynb | muatik/dm | mit |
Again, the reconstructed matrix is very similar to the original one. And the total error is still small.
Now we can ask the question that which rank should we pick? There is trade-off that when you use more rank, you get closer to the original matrix and have less error, however you need to keep more data. On the othe... | reconstruct(U, S, V, 2)
calcError(A, reconstruct(U, S, V, 2))
A = np.mat([
[4, 5, 4, 0, 4, 0, 0, 1, 0, 1, 2, 1],
[5, 3, 5, 5, 0, 1, 0, 0, 2, 0, 0, 2],
[0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 5, 0, 0, 4, 5, 4, 0],
[0, 1, 1, 0, 0, 4, 3, 5, 5, 3... | SingularValueDecomposition.ipynb | muatik/dm | mit |
As it can be seen above, more rank is used, less error occur. From another perspective, we get closer to the original data by increasing rank number.
On the other hand, after a certain rank, using more rank will not contribute as much as
Let's compare a reconstructed column to the original one by just naked eyes. Even... | print("Original:\n", A[:,10])
print("Reconstructed:\n", reconstruct(U, S, V, 4)[:,10])
imread("data/pacman.png", flatten=True).shape
A = np.mat(imread("data/pacman.png", flatten=True))
U, S, V = np.linalg.svd(A)
A.shape, U.shape, S.shape, V.shape
for rank in range(1, len(S)):
rA = reconstruct(U, S, V, rank)
... | SingularValueDecomposition.ipynb | muatik/dm | mit |
Double check that we're using raw fluxes (norm = False): | if Starfish.config["grid"]["norm"] == False : print("All good.")
h5i.grid_points.shape | demo7/raw/mixture_model_01_exploratory.ipynb | gully/starfish-demo | mit |
Let's load the flux of each model grid point and compute the mean flux ratio with every other model grid point.
There will be $N_{grid} \times N_{grid}$ pairs of flux ratios, only half of which are unique. | N_grid, D_dim = h5i.grid_points.shape
N_tot = N_grid*N_grid
d_grd = np.empty((N_tot, D_dim*2))
f_rat = np.empty(N_tot)
c = 0
for i in np.arange(N_grid):
print(i, end=' ')
for j in np.arange(N_grid):
d_grd[c] = np.hstack((h5i.grid_points[i], h5i.grid_points[j]))
f_rat[c] = np.mean(h5i.load_flu... | demo7/raw/mixture_model_01_exploratory.ipynb | gully/starfish-demo | mit |
We now have a six dimensional design matrix and a scalar that we can fit to. | d_grd.shape, f_rat.shape
from scipy.interpolate import LinearNDInterpolator
interp_f_rat = LinearNDInterpolator(d_grd, f_rat)
interp_f_rat(6000,4.0, 0, 6200, 5.0, -1.0)
np.mean(h5i.load_flux([6000, 4.0, 0]))/np.mean(h5i.load_flux([6200, 5.0, -1.0])) | demo7/raw/mixture_model_01_exploratory.ipynb | gully/starfish-demo | mit |
Checks out.
So now we can produce $q_m$ on demand!
Just a reminder... we have to do this for each order. The next step is to figure out how to implement this efficiently in parallel operations. | spec = h5i.load_flux(h5i.grid_points[i])
h5i.wl.shape, spec.shape
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(h5i.wl, spec)
Starfish.config["data"]["orders"] | demo7/raw/mixture_model_01_exploratory.ipynb | gully/starfish-demo | mit |
Load Iris Flower Data | # Load data
iris = datasets.load_iris()
X = iris.data | machine-learning/dbscan_clustering-Copy1.ipynb | tpin3694/tpin3694.github.io | mit |
Conduct Agglomerative Clustering
In scikit-learn, AgglomerativeClustering uses the linkage parameter to determine the merging strategy to minimize the 1) variance of merged clusters (ward), 2) average of distance between observations from pairs of clusters (average), or 3) maximum distance between observations from pai... | # Create meanshift object
clt = AgglomerativeClustering(linkage='complete',
affinity='euclidean',
n_clusters=3)
# Train model
model = clt.fit(X_std) | machine-learning/dbscan_clustering-Copy1.ipynb | tpin3694/tpin3694.github.io | mit |
Show Cluster Membership | # Show cluster membership
model.labels_ | machine-learning/dbscan_clustering-Copy1.ipynb | tpin3694/tpin3694.github.io | mit |
We create the visibility.
This just makes the uvw, time, antenna1, antenna2, weight columns in a table | times = numpy.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) * (numpy.pi / 12.0)
frequency = numpy.array([1e8])
channel_bandwidth = numpy.array([1e7])
reffrequency = numpy.max(frequency)
phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-45.0 * u.deg, frame='icrs', equinox='J2000')
vt = create_visibility(lowcore, times, fr... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Advise on wide field parameters. This returns a dictionary with all the input and calculated variables. | advice = advise_wide_field(vt, wprojection_planes=1) | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Plot the synthesized UV coverage. | if doplot:
plt.clf()
plt.plot(vt.data['uvw'][:, 0], vt.data['uvw'][:, 1], '.', color='b')
plt.plot(-vt.data['uvw'][:, 0], -vt.data['uvw'][:, 1], '.', color='r')
plt.xlabel('U (wavelengths)')
plt.ylabel('V (wavelengths)')
plt.show()
plt.clf()
plt.plot(vt.data['uvw'][:, 0], vt.data['u... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Show the planar nature of the uvw sampling, rotating with hour angle
Create a grid of components and predict each in turn, using the full phase term including w. | npixel = 512
cellsize=0.001
facets = 4
flux = numpy.array([[100.0]])
vt.data['vis'] *= 0.0
model = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
spacing_pixels = npixel // facets
log.info('Spacing in pixels = %s' % spacing_pixels)
spacing = 180.0 * cellsize * spacing_pixels / numpy.pi
centers = ... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Make the dirty image and point spread function using the two-dimensional approximation:
$$V(u,v,w) =\int I(l,m) e^{2 \pi j (ul+um)} dl dm$$
Note that the shape of the sources vary with position in the image. This space-variant property of the PSF arises from the w-term neglected in the two-dimensional invert. | arlexecute.set_client(use_dask=True)
dirty = create_image_from_visibility(vt, npixel=512, cellsize=0.001,
polarisation_frame=PolarisationFrame("stokesI"))
vt = weight_visibility(vt, dirty)
future = invert_list_arlexecute_workflow([vt], [dirty], context='2d')
dirty, sumwt = arlexe... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
This occurs because the Fourier transform relationship between sky brightness and visibility is only accurate over small fields of view.
Hence we can make an accurate image by partitioning the image plane into small regions, treating each separately and then glueing the resulting partitions into one image. We call thi... | dirtyFacet = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
future = invert_list_arlexecute_workflow([vt], [dirtyFacet], facets=4, context='facets')
dirtyFacet, sumwt = arlexecute.compute(future, sync=True)[0]
if doplot:
show_image(dirtyFacet)
print("Max, min in dirty image = %.6f, %.6f, sum... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
That was the best case. This time, we will not arrange for the partitions to be centred on the sources. | dirtyFacet2 = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
future = invert_list_arlexecute_workflow([vt], [dirtyFacet2], facets=2, context='facets')
dirtyFacet2, sumwt = arlexecute.compute(future, sync=True)[0]
if doplot:
show_image(dirtyFacet2)
print("Max, min in dirty image = %.6f, %.6f... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Another approach is to partition the visibility data by slices in w. The measurement equation is approximated as:
$$V(u,v,w) =\sum_i \int \frac{ I(l,m) e^{-2 \pi j (w_i(\sqrt{1-l^2-m^2}-1))})}{\sqrt{1-l^2-m^2}} e^{-2 \pi j (ul+um)} dl dm$$
If images constructed from slices in w are added after applying a w-dependent ... | if doplot:
wterm = create_w_term_like(model, phasecentre=vt.phasecentre, w=numpy.max(vt.w))
show_image(wterm)
plt.show()
dirtywstack = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
future = invert_list_arlexecute_workflow([vt], [dirtywstack], vis_slices=101, context='wstack')
dirtyws... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
The w-term can also be viewed as a time-variable distortion. Approximating the array as instantaneously co-planar, we have that w can be expressed in terms of $u,v$
$$w = a u + b v$$
Transforming to a new coordinate system:
$$ l' = l + a (\sqrt{1-l^2-m^2}-1))$$
$$ m' = m + b (\sqrt{1-l^2-m^2}-1))$$
Ignoring changes in ... | for rows in vis_timeslice_iter(vt):
visslice = create_visibility_from_rows(vt, rows)
dirtySnapshot = create_image_from_visibility(visslice, npixel=512, cellsize=0.001, npol=1, compress_factor=0.0)
future = invert_list_arlexecute_workflow([visslice], [dirtySnapshot], context='2d')
dirtySnapshot, sumwt = ... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
This timeslice imaging leads to a straightforward algorithm in which we correct each time slice and then sum the resulting timeslices. | dirtyTimeslice = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
future = invert_list_arlexecute_workflow([vt], [dirtyTimeslice], vis_slices=vis_timeslices(vt, 'auto'),
padding=2, context='timeslice')
dirtyTimeslice, sumwt = arlexecute.compute(future, sync=Tru... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Finally we try w-projection. For a fixed w, the measurement equation can be stated as as a convolution in Fourier space.
$$V(u,v,w) =G_w(u,v) \ast \int \frac{I(l,m)}{\sqrt{1-l^2-m^2}} e^{-2 \pi j (ul+um)} dl dm$$
where the convolution function is:
$$G_w(u,v) = \int \frac{1}{\sqrt{1-l^2-m^2}} e^{-2 \pi j (ul+um + w(\sq... | dirtyWProjection = create_image_from_visibility(vt, npixel=512, cellsize=0.001, npol=1)
gcfcf = create_awterm_convolutionfunction(model, nw=101, wstep=800.0/101, oversampling=8,
support=60,
use_aaf=True)
futur... | workflows/notebooks/imaging-wterm_arlexecute.ipynb | SKA-ScienceDataProcessor/algorithm-reference-library | apache-2.0 |
Define the features and preprocess the car evaluation data set
We'll preprocess the attributes into redundant features, such as using an integer index (linear) to represent a value for an attribute, as well as also using a one-hot encoding for each attribute's possible values as new features. Despite the fact that this... | input_labels = [
["buying", ["vhigh", "high", "med", "low"]],
["maint", ["vhigh", "high", "med", "low"]],
["doors", ["2", "3", "4", "5more"]],
["persons", ["2", "4", "more"]],
["lug_boot", ["small", "med", "big"]],
["safety", ["low", "med", "high"]],
]
output_labels = ["unacc", "acc", "good", "... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Train simple decision trees (here using XGBoost) to fit the data set:
First, let's define some hyperparameters, such as the depth of the tree. |
num_rounds = 1 # Do not use boosting for now, we want only 1 decision tree per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
# Let's use a max_depth of 4 for the sole goal of simplifying the visual representation produced
# (ideally, a tree would be deeper to classify perfectly on that... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Plot and save the trees (one for each class):
The 4 trees of the classifer (one tree per class) will each output a number that represents how much it is probable that the thing to classify belongs to that class, and it is by comparing the output at the end of all the trees for a given example that we could get the maxi... | def plot_first_trees(bst, output_labels, trees_name):
"""
Plot and save the first trees for multiclass classification
before any boosting was performed.
"""
for tree_idx in range(len(output_labels)):
class_name = output_labels[tree_idx]
graph_save_path = os.path.join(
"ex... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Note that the above trees can be viewed here online:
https://github.com/Vooban/Decision-Trees-For-Knowledge-Discovery/tree/master/exported_xgboost_trees
Plot the importance of each input features for those simple decision trees:
Note here that it is the feature importance according to our simple, shallow trees. More co... | fig, ax = plt.subplots(figsize=(12, 7))
xgb.plot_importance(bst, ax=ax)
plt.show() | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Let's now generate slightly more complex trees to aid inspection
<p align="center">
<a href="http://theinceptionbutton.com/" ><img src="deeper.jpg" /></a>
</p>
Let's go deeper and build deeper trees. However, those trees are not maximally complex since XGBoost is rather built to boost over forests of small trees tha... | num_rounds = 1 # Do not use boosting for now, we want only 1 decision tree per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
# Let's use a max_depth of 4 for the sole goal of simplifying the visual representation produced
# (ideally, a tree would be deeper to classify perfectly on that ... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Note that the above trees can be viewed here online:
https://github.com/Vooban/Decision-Trees-For-Knowledge-Discovery/tree/master/exported_xgboost_trees
Finding a perfect classifier rather than an easily explainable one
We'll now use boosting. The resulting trees can't be explained as easily as the previous ones, since... | num_rounds = 10 # 10 rounds of boosting, thus 10 trees per class.
num_classes = len(output_labels)
num_trees = num_rounds * num_classes
param = {
'max_depth': 20,
'eta': 1.43,
'objective': 'multi:softprob',
'num_class': num_classes,
}
bst = xgb.train(param, dtrain, early_stopping_rounds=1, num_boost... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
In our case, note that it is possible to have an error of 0 (thus an accuracy of 100%) since we have a dataset that represents a function, which is mathematically deterministic and could be interpreted as programmatically pure in the case it would be implemented. But wait... we just implemented and recreated the functi... | # Some plot options from the doc:
# importance_type : str, default "weight"
# How the importance is calculated: either "weight", "gain", or "cover"
# "weight" is the number of times a feature appears in a tree
# "gain" is the average gain of splits which use the feature
# "cover" is the average coverage... | Decision-Trees-For-Knowledge-Discovery-With-XGBoost.ipynb | Vooban/Decision-Trees-For-Knowledge-Discovery | mit |
Get Authorization URL
Available per client. For Den it is:
https://home.nest.com/login/oauth2?client_id=54033edb-04e0-4fc7-8306-5ed6cb7d7b1d&state=STATE
Where STATE should be a value that is:
Used to protect against cross-site request forgery attacks
Format: any unguessable string
We strongly recommend that you use... | import uuid
def _get_state():
"""Get a unique id string."""
return str(uuid.uuid1())
_get_state() | notebooks/Authorization.ipynb | krismolendyke/den | mit |
Create Authorization URL Helper | API_PROTOCOL = "https"
API_LOCATION = "home.nest.com"
from urlparse import SplitResult, urlunsplit
from urllib import urlencode
def _get_url(path, query, netloc=API_LOCATION):
"""Get a URL for the given path and query."""
split = SplitResult(scheme=API_PROTOCOL, netloc=netloc, path=path, query=query, fragment... | notebooks/Authorization.ipynb | krismolendyke/den | mit |
Get Authorization Code
get_auth_url() returns a URL that should be visited in the browser to get an authorization code.
For Den, this authorization code will be a PIN. | !open "{get_auth_url()}" | notebooks/Authorization.ipynb | krismolendyke/den | mit |
Cut and paste that PIN here: | pin = "" | notebooks/Authorization.ipynb | krismolendyke/den | mit |
Get Access Token
Use the pin code to request an access token. https://developer.nest.com/documentation/cloud/authorization-reference/ | def get_access_token_url(client_id=DEN_CLIENT_ID, client_secret=DEN_CLIENT_SECRET, code=pin):
"""Get an access token URL for the given client id."""
path = "oauth2/access_token"
query = urlencode({"client_id": client_id,
"client_secret": client_secret,
"code":... | notebooks/Authorization.ipynb | krismolendyke/den | mit |
POST to that URL to get a response containing an access token: | import requests
r = requests.post(get_access_token_url())
print r.status_code
assert r.status_code == requests.codes.OK
r.json() | notebooks/Authorization.ipynb | krismolendyke/den | mit |
It seems like the access token can only be created once and has a 10 year expiration time. | access_token = r.json()["access_token"]
access_token | notebooks/Authorization.ipynb | krismolendyke/den | mit |
Preprocessing: Principal Component Analysis
1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable
size, while maintaining most of the information in the dataset. Here it is useful to use a variant
of PCA called RandomizedPCA, which is an approximation of PCA that can be much f... | from sklearn import decomposition
pca = decomposition.RandomizedPCA(n_components=150, whiten=True)
pca.fit(X_train)
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print(X_train_pca.shape)
print(X_test_pca.shape) | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
The classifier is correct on an impressive number of images given the simplicity
of its learning model! Using a linear classifier on 150 features derived from
the pixel-level data, the algorithm correctly identifies a large number of the
people in the images.
Again, we can
quantify this effectiveness using one of seve... | from sklearn import metrics
y_pred = clf.predict(X_test_pca)
print(metrics.classification_report(y_test, y_pred, target_names=lfw_people.target_names)) | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
Another interesting metric is the confusion matrix, which indicates how often
any two items are mixed-up. The confusion matrix of a perfect classifier
would only have nonzero entries on the diagonal, with zeros on the off-diagonal. | print(metrics.confusion_matrix(y_test, y_pred))
print(metrics.f1_score(y_test, y_pred)) | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
Pipelining
Above we used PCA as a pre-processing step before applying our support vector machine classifier.
Plugging the output of one estimator directly into the input of a second estimator is a commonly
used pattern; for this reason scikit-learn provides a Pipeline object which automates this
process. The above pro... | from sklearn.pipeline import Pipeline
clf = Pipeline([('pca', decomposition.RandomizedPCA(n_components=150, whiten=True)),
('svm', svm.LinearSVC(C=1.0))])
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(metrics.confusion_matrix(y_pred, y_test)) | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
Aggregation Operators
$project - shape documents e.g. select
$match - filtering
$skip - skip at start
$limit - limit after some
$unwind - for every field of the array field on which it is used it will create an instance of document containing the values of the field. This can be used for grouping
Match operator
Who ... | query = [
{"$match": {"user.friends_count": {"$gt": 0},
"user.followers_count": {"$gt": 0}}},
{"$project": {"ratio": {"$divide": ["$user.followers_count",
"$user.friends_count"]},
"screen_name": "$user.screen_name"}},
{"$sort": {"rat... | udacity_data_science_notes/Data_Wrangling_with_MongoDB/lesson_05/lesson_05.ipynb | anshbansal/anshbansal.github.io | mit |
For $match we use the same syntax that we use for read operations
Project operator
include fields from the original document
insert computed fields
rename fields
create fields that hold sub documents
Unwind operator
need to use array values somehow
Let's try and find who included the most user mentions | query = [
{"$unwind": "$entities.user_mentions"},
{"$group": {"_id": "$user.screen_name",
"count": {"$sum": 1}}},
{"$sort": {"count": -1}}
]
aggregate_and_show(collection, query) | udacity_data_science_notes/Data_Wrangling_with_MongoDB/lesson_05/lesson_05.ipynb | anshbansal/anshbansal.github.io | mit |
group operators
$sum
$first
$last
$max
$min
$avg
array operators
- $push
- $addToSet | #get unique hashtags by user
query = [
{"$unwind": "$entities.hashtags"},
{"$group": {"_id": "$user.screen_name",
"unique_hashtags": {
"$addToSet": "$entities.hashtags.text"
}}},
{"$sort": {"_id": -1}}
]
aggregate_and_show(collection, query)
# find numbe... | udacity_data_science_notes/Data_Wrangling_with_MongoDB/lesson_05/lesson_05.ipynb | anshbansal/anshbansal.github.io | mit |
Analysis of gapick tool genetic algorithm's (GA) run
Read more about PSF stars finding tool gapick in astwro documentation.
Results directory
gapick wrotes several results into directory specified by --out_dir parameter. Set path to results dir below: | resultpath = '~/tmp/gapick_fine' | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Checkout the content of this directory | import os
os.chdir(os.path.expanduser(resultpath))
!ls | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
For each generation of GA there are three files:
* genXXX.gen - dump of all individuals as boolean matrix
* genXXX.lst - daophot LST file with PSF stars of best individual
* genXXX.reg - DS9 region file corresponding to LST file
Also, there are three links to most recent versions of that files: | !ls -l gen_last.* | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Such links are maintained during execution of gapick script which allows partial results analysis while script is running.
*.gen files structure is shown below: | !head gen_last.gen | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Each line is one individual, each column is one candidate star. 1 means that candidate is a member of individual.
Moreover there is about.txt with information about parameters: | !cat about.txt | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Also several optput files of daophot commands are included, as well as opt files with used configuration.
Evolution analysis
logbook.pkl file contains statistics collected by deap module during evolution. | import deap, pickle
f = open('logbook.pkl')
logbook = pickle.load(f) | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Plot values of chi, and number of selected stars, against generation number | gen = logbook.select('gen')
chi_mins = logbook.chapters["fitness"].select("min")
stars_avgs = logbook.chapters["size"].select("avg")
fig, ax1 = subplots()
fig.set_size_inches(10,6)
line1 = ax1.plot(gen, chi_mins, "b-", label="Minimum chi")
ax1.set_xlabel("Generation")
ax1.set_ylabel("chi", color="b")
for tl in ax1.get... | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Spośród wszystkich gwiazd, algorytm wybrał 100 (domyślna wartość parametru --stars_to_pick) kandydatów przy pomocy polecenia daophot PICK. Następnie poleceniem PSF obliczył point spread function na postawie tego pełnego zbioru i uzyskał błędy dopasowania profilu dla tych gwiazd (Profile errors zwracane przez daophot PS... | spectrum = logbook.select('spectrum')
x_starno = range(len(spectrum[0]))
fig, ax1 = plt.subplots()
fig.set_size_inches(30,10)
#cont = ax1.contourf(x_starno, gen, spectrum)
cont = ax1.imshow(spectrum, interpolation='nearest', cmap=plt.cm.YlGnBu)
ax1.set_xlabel("Star")
ax1.set_ylabel("Generation")
plt.colorbar(cont)
p... | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Na wykresie widać jak w ciągu około 20 populacji wyłaniają się wyraźni liderzy. Niemniej również w późniejszych generacjach występują zmiany. Pomiędzy 70 a 80 generacją algorytm "wymienił" jedną z gwiazd na inną, ktora w poczatkowych generacjach nie była preferowana.
Comaprision with other evolutions
Liczebność zbiorów... | resultpaths = [
'~/tmp/gapick_fine',
'~/tmp/gapick_simple',
]
labels = [
'fine',
'simple',
] | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Pobranie danych logów z wyników | logbook = []
resultpaths = [os.path.expanduser(p) for p in resultpaths]
for p in resultpaths:
f = open(os.path.join(p,'logbook.pkl'))
logbook.append(pickle.load(f))
gens = []
chi_min = []
stars_av = []
for l in logbook:
gens.append(l.select('gen'))
chi_min.append(l.chapters["fitness"].select("min"))
... | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
Sprawdźmy jak różne bądź podobne są skrajne rozwiązania, zestawiając "histogramy" ich przebiegu. | spectrum = [ l.select('spectrum') for l in logbook]
x_starno = range(len(spectrum[0][0]))
fig, ax = subplots(2,1)
fig.subplots_adjust(hspace=0)
fig.set_size_inches(10,10)
ax[1].set_ylim(0, len(gen)) # flip
ax[0].imshow(spectrum[0], interpolation='nearest', cmap=plt.cm.YlGnBu)
ax[1].imshow(spectrum[-1], interpolatio... | examples/gapick_analyse.ipynb | majkelx/astwro | mit |
1. Clustering | #Som elibraries
from sklearn import preprocessing
from sklearn.cluster import DBSCAN, KMeans
#Read teh data, dropna, get sample
df = pd.read_csv("data/big3_position.csv",sep="\t").dropna()
df["Revenue"] = np.log10(df["Revenue"])
df["Assets"] = np.log10(df["Assets"])
df["Employees"] = np.log10(df["Employees"])
df["Mark... | class8/class8_impute.ipynb | jgarciab/wwd2017 | gpl-3.0 |
1a. Clustering with K-means
k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells.
Other methods: http://scikit-learn.org/stab... | #Get labels of each row and add a new column with the labels
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
labels = kmeans.labels_
df["kmeans_labels"] = labels
sns.lmplot(x="MarketCap",y="Assets",hue="kmeans_labels",fit_reg=False,data=df) | class8/class8_impute.ipynb | jgarciab/wwd2017 | gpl-3.0 |
1b. Clustering with DBSCAN
The DBSCAN algorithm views clusters as areas of high density separated by areas of low density. Due to this rather generic view, clusters found by DBSCAN can be any shape, as oppos | #Get labels of each row and add a new column with the labels
db = DBSCAN(eps=1, min_samples=10).fit(X)
labels = db.labels_
df["dbscan_labels"] = labels
sns.lmplot(x="MarketCap",y="Assets",hue="dbscan_labels",fit_reg=False,data=df)
Image(url="http://scikit-learn.org/stable/_images/sphx_glr_plot_cluster_comparison_0011.... | class8/class8_impute.ipynb | jgarciab/wwd2017 | gpl-3.0 |
1c. Hierarchical clustering
Keeps aggreagating from a point | import scipy
import pylab
import scipy.cluster.hierarchy as sch
# Generate distance matrix based on the difference between rows
D = np.zeros([4,4])
for i in range(4):
for j in range(4):
D[i,j] = np.sum(np.abs(X[:,i]-X[:,j])) #Euclidean distance or mutual information are also common
print(D)
#Crea... | class8/class8_impute.ipynb | jgarciab/wwd2017 | gpl-3.0 |
2. Imputation of missing data (fancy) | #Required libraries
!conda install tensorflow -y
!pip install fancyimpute
!pip install pydot_ng
import sklearn.preprocessing
import sklearn
#Read the data again but do not
df = pd.read_csv("data/big3_position.csv",sep="\t")
df["Revenue"] = np.log10(df["Revenue"])
df["Assets"] = np.log10(df["Assets"])
df["Employees"... | class8/class8_impute.ipynb | jgarciab/wwd2017 | gpl-3.0 |
Sample usage
Let's test our JaccardScoreCallback class with a Keras model. | # Model / data parameters
num_classes = 10
input_shape = (28, 28, 1)
# The data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure im... | examples/keras_recipes/ipynb/sklearn_metric_callbacks.ipynb | keras-team/keras-io | apache-2.0 |
Python uses the $\LaTeX$ language to typeset equations.
Use a single set of $ to make your $\LaTeX$ inline and a double set $$ to center
This code will produce the output:
$$ \int \cos(x)\ dx = \sin(x) $$
Use can use $\LaTeX$ in plots: | plt.style.use('ggplot')
x = np.linspace(0,2*np.pi,100)
y = np.sin(5*x) * np.exp(-x)
plt.plot(x,y)
plt.title("The function $y\ =\ \sin(5x)\ e^{-x}$")
plt.xlabel("This is in units of 2$\pi$")
plt.text(2.0, 0.4, '$\Delta t = \gamma\, \Delta t$', color='green', fontsize=36) | 08_Python_LaTeX.ipynb | UWashington-Astro300/Astro300-A16 | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.