markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Multiple linear regression Add topings to our model of pizza price prediction
from numpy.linalg import inv from numpy import dot, transpose X = [[1, 6, 2], [1, 8, 1], [1, 10, 0], [1, 14, 2], [1, 18, 0]] X y = [[7], [9], [13], [17.5], [18]] #Solve using linear algebra dot(inv(dot(transpose(X),X)), dot(transpose(X),y)) #Solve using numpy least squares procedure from numpy.linalg import lstsq l...
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Polynomial regression Use PolynomialFeatures to transform the data
from sklearn.preprocessing import PolynomialFeatures X_train = [[6], [8], [10], [14], [18]] y_train = [[7], [9], [13], [17.5], [18]] X_test = [[6], [8], [11], [16]] y_test = [[8], [12], [15], [18]] regressor = LinearRegression() regressor.fit(X_train, y_train) xx = np.linspace(0, 26, 100) xx yy = regressor.pre...
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Apply linear regression on Wine dataset from UCI
import pandas as pd target_url = ("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv") df = pd.read_csv(target_url,header=0, sep=";") df.head() df.describe() plt.scatter(df['alcohol'], df['quality']) plt.xlabel("Alcohol") plt.ylabel("Quality") plt.title("Alcohol against Qual...
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Fit and evaluate the model
from sklearn.cross_validation import train_test_split #Split into feature and target, train and test X = df[list(df.columns)[:-1]] y = df['quality'] X.head() y.tail() X_train, X_test, y_train, y_test = train_test_split(X, y) regressor = LinearRegression() regressor.fit(X_train, y_train) y_predictions = regressor....
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Cross validation
#Make cross validation from sklearn.cross_validation import cross_val_score scores = cross_val_score(regressor, X, y, cv = 5) print(scores.mean(), scores)
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Fitting using gradient descent
from sklearn.datasets import load_boston from sklearn.linear_model import SGDRegressor from sklearn.preprocessing import StandardScaler data = load_boston() X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) X_scaler = StandardScaler() y_scaler = StandardScaler() X_train = X_scaler.fit_trans...
Chapters/Two/Simple Linear Regression.ipynb
fadeetch/Mastering-ML-Python
mit
Load data (in LiPD format)
loadLipds() f1 = getCsv("Crystal2013.lpd") d18O = f1["Crystal2013.paleo1measurement1.csv"]["d18O_VPDB"] d18O = np.asarray(d18O) depth = f1["Crystal2013.paleo1measurement1.csv"]["Depth"] depth = np.asarray(depth) depth = depth /10.0 #depth in cm
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Load chronology information
age_c = f1["Crystal2013.chron1measurement1.csv"]["230Th Age (yr BP) (corrected)"] age_c = np.asarray(age_c) age_c = np.insert(age_c,0,-57) #insert the top age depth_age = f1["Crystal2013.chron1measurement1.csv"]["Depth (mm)"] depth_age = np.asarray(depth_age) depth_age = np.insert(depth_age,0,0.05) age_sd = f1["Cryst...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
plot raw age model
# plot age model plt.rc('text', usetex=True,) plt.rc('font', family='sans-serif') # create figure f, (ax1, ax2) = plt.subplots(2, 1) f.set_figheight(9); f.set_figwidth(8) ax1.spines["top"].set_visible(False) ax1.spines["right"].set_visible(False) ax1.errorbar(depth_age,age_c,age_sd) ax1.set_xlabel(r'Depth (mm)') a...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Preparation for the age modelling
# convert to ages BP year_BP = age_c year_CE = 1950 - year_BP top_date = 2007 year_top = year_BP + top_date - 1950 nyears = int(year_CE.max()-year_CE.min())+1 positions = FloatVector(depth_age/10.0)# position in core in cm ages = FloatVector(year_BP)# age estimate ages_CE = FloatVector(year_top)# age estimate sd = Fl...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Generate different age-depth realizations by using Bchron age model
Bchron=importr('Bchron') haha = Bchron.Bchronology(ages=ages, ageSds=sd, positions=positions, iterations=10000, burn=2000, thin=8, extractDate=topDate, calCurves=calCurves, predictPositions=predictPositions)
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Retrieve the result of estimated ages
# The variable 'theta' is the posterior estimated values of the ages, and is stored as # the first matrix of the List Vector class 'ages' theta = haha[0] theta=np.array(theta) thetaPredict = haha[4] thetaPredict=np.array(thetaPredict) # Save depth horizons depths=np.array(predictPositions) depth_horizons=depths[:-1]...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Plot the age model
# PLOT IT OUT x = depth_horizons*10 f2 = plt.figure(figsize=(10,8)) ax = plt.axes() ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.fill_between(x, chronQ[:,0], chronQ[:,2], facecolor='Silver',edgecolor='Silver',lw=0.0) # see...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
plot timeseries quantiles
f, ax = plt.subplots(1, 1) f.set_figheight(6); f.set_figwidth(8) chronQ = mquantiles(chronCE, prob=[0.025, 0.5, 0.975], axis=1) Xr = d18O[:-1] hp,= plt.plot(chronQ[:,0], Xr, lw=0.5, color='silver',ls='dashed') hl,= plt.plot(chronQ[:,2], Xr, lw=0.5, color='silver') hm,= plt.plot(chronQ[:,1], Xr, lw=1.0, color='DarkBlue...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Now we are going to correlate speleothem $\delta^{18}O$ with sea surface temperature First read monthly sea surface temperature from a netCDF file
#read Kaplan SST nc = xray.open_dataset('/Users/hujun/Downloads/sst.mon.anom.nc') lat0 = nc['lat'] lon0 = nc['lon'] sst = nc['sst'] nlat=lat0.shape[0] nlon=lon0.shape[0] sst_ann=sst[19:1831:12,:,:]
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Prepare functions for filtering
def butter_lowpass(cutoff, fs, order=3): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def filter(x, cutoff, axis, fs=1.0, order=3): b, a = butter_lowpass(cutoff, fs, order=order) y = filtfilt(b, a, x, axis=axis) retur...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Get the annual mean SST from 1857-2007
#annual mean for i in range(sst_ann.shape[0]): sst_ann[i,:,:]=np.mean(sst[i*12+19:(i+1)*12+19,:,:],axis=0) #sst_ann_fil=filter(sst_ann,1.0/30,0) sst_ann_fil=sst_ann
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Read age model results
crys = np.load('Crystal_Bchron.npz') chronCE = crys['chronCE'] depth = crys['depth_horizons'] chronQ = mquantiles(chronCE, prob=[0.025, 0.5, 0.975], axis=1)
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Prepare the function for deleting repeated calendar year in the age model result
def coarse_grain(t,X): tu = np.unique(t) # find unique values nu = tu.shape[0] Xu = np.zeros(nu,) for j in range(nu): Xu[j] = np.mean(X[np.where(t==tu[j])]) return (tu,Xu)
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Interpolate $\delta^{18}O$ on the annual scale
#interpolation d18O_multi=np.zeros((chronCE.shape[1],sst_ann_fil.shape[0])) sst_corr=np.zeros((chronCE.shape[1],nlat,nlon)) for it in range(chronCE.shape[1]): tu, Xu = coarse_grain(chronCE[:,it],Xr) #interpolation tck = interpolate.splrep(tu,Xu,s=1) xnew = range(1857,2008,1) ynew = interpolate.sple...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Calculate correlations between the each realization of $\delta^{18}O$ and SST in each grid cell
#correlation #sst_ann_new=sst_ann_fil.transpose(1,2,0) sst_ann_new=sst_ann_fil.transpose("lat","lon","time") d18O_new=np.transpose(d18O_fil) sst_ano=np.ma.anomalies(sst_ann_new,axis=2) d18O_ano=np.ma.anomalies(d18O_new,axis=0) nomi=np.dot(sst_ano,d18O_ano) sst_sd=np.sum(sst_ano**2,axis=2) d18O_sd=np.sum(d18O_ano**2,a...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Test significance of the calculated correlations (replace the Nsample to your raw sample size)
#t-test for correlation corrQ975= corrQ_new[:,:,2] corrQ025= corrQ_new[:,:,0] corrQ050= corrQ_new[:,:,1] d18O_coef, d18O_sigma = alg.AR_est_YW(d18O_median_ano,1) neff_array=sst_ano[:,:,0] latt,lont=[],[] pval_025=[] pval_975=[] pval_med=[] Nsample = 151 for ilat in range(nlat): for ilon in range(nlon): i...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Check and plot p-values in the FDR procedure
#check i/m vs. p-values indexm = np.arange(1,len(pval_975)+1,1) im = 1.0*indexm / len(pval_975) thres = 0.05*im pval_975_s = sorted(pval_975) #pval_025_s = sorted(pval_025) smaller=[] small_index=[] larger=[] large_index=[] n=0 for pp in pval_975_s: #for pp in pval_025_s: if pp <=0.05: smaller.append(pp) ...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
FDR procedure
#start FDR procedure pvalr_975 = FloatVector(pval_975) pvalr_025 = FloatVector(pval_025) pvalr_med = FloatVector(pval_med) r.source("fdr.R") #sig_975 = r.fdr(pvalr_975,method="original",adjustment_method="mean") #sig_025 = r.fdr(pvalr_025,method="original",adjustment_method="mean") #sig_med = r.fdr(pvalr_med,method="o...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Plot figures of distributions of correlations (median, IQR, 2.5% quantile, 97.5% qunatile)
#plot figures map = Basemap(projection='robin',resolution='l',lat_0=0,lon_0=180) #map.drawcoastlines() #map.fillcontinents(color='gray') #map.drawmapboundary() #map.drawmeridians(np.arange(0,360,30)) #map.drawparallels(np.arange(-90,90,30)) lons, lats = np.meshgrid(lon0, lat0) x,y=map(lons,lats) fig=plt.figure(figsize...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Plot the spectra by using the MTM method First load age model results
#d18O from McCabe paper data_mc = genfromtxt('data/McCabe_crystal.txt', delimiter=',') d18O_mc = data_mc[0:,2] d18O_mc_rm = d18O_mc-np.mean(d18O_mc) # load Bchron data crys = np.load('Crystal_Bchron.npz') chronCE = crys['chronCE'] depth = crys['depth_horizons'] chronQ = mquantiles(chronCE, prob=[0.025, 0.5, 0.975], a...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Calculate the spectra of the median $\delta^{18}O$ from Bchron results
def spline_interp(tu,Xu,tstart,tend): tck = interpolate.splrep(tu,Xu,s=1) xnew = range(tstart,tend,1) ynew = interpolate.splev(xnew,tck) ynew_rm = ynew-np.mean(ynew) return ynew_rm #MTM spectrum for the median d18O from Bchron tu_bchron, Xu_bchron = coarse_grain(chronQ[:,1],Xr) ynew_bchron = spline...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Calculate all possible spectras from Bchron results
for it in range(chronCE.shape[1]): tu, Xu = coarse_grain(chronCE[:,it],Xr) ynew_rm = spline_interp(tu,Xu,1000,2008) f, psd_mt, nu = alg.multi_taper_psd(ynew_rm,Fs=1.0,adaptive=False,jackknife=False) psd_multi[:,it]=psd_mt coef,sigma=alg.AR_est_YW(ynew_rm,1) X_ar, noise, aph = utils.ar_generato...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Plot the spectra
pq = mquantiles(pmtm_ar, prob=[0.025, 0.5, 0.975], axis=1) psdQ = mquantiles(psd_multi, prob=[0.025, 0.5, 0.975], axis=1) #plot the figure pertick=np.array([200, 100 ,50, 20,10,8, 6,4, 2]) pertick_labels=(['200', '100' ,'50', '20','10','8' ,'6','4', '2']) xtick=(1.0/pertick) plt.loglog(f_m, psd_mt_m,label=r'$\delt...
CrystalCave.ipynb
ClimateTools/Correlation_EPSL
mit
Adding additional latent variables to the likelihood The standard GPyTorch variational objects will take care of inferring the latent functions $f_1 \ldots f_k$. However, we do need to add the additional latent variables $z_i$ to the models. We will do so by creating a custom likelihood that models: $$ \sum_{z_i=1}^k p...
class ClusterGaussianLikelihood(gpytorch.likelihoods.Likelihood): def __init__(self, num_tasks, num_clusters): super().__init__() # These are parameters/buffers for the cluster assignment latent variables self.register_buffer("prior_cluster_logits", torch.zeros(num_tasks, num_cluste...
examples/07_Pyro_Integration/Clustered_Multitask_GP_Regression.ipynb
jrg365/gpytorch
mit
Constructing the PyroGP model The PyroGP model is essentially the same as the model we used in the simple example, except for two changes We now will use our more complicated ClusterGaussianLikelihood The latent function should be vector valued to correspond to the k latent functions. As a result, we will learn a batc...
class ClusterMultitaskGPModel(gpytorch.models.pyro.PyroGP): def __init__(self, train_x, train_y, num_functions=2, reparam=False): num_data = train_y.size(-2) # Define all the variational stuff inducing_points = torch.linspace(0, 1, 64).unsqueeze(-1) variational_distribution = gpytor...
examples/07_Pyro_Integration/Clustered_Multitask_GP_Regression.ipynb
jrg365/gpytorch
mit
Every wxPython app is an instance of wx.App. For most simple applications you can use wx.App as is. When you get to more complex applications you may need to extend the wx.App class. The "False" parameter means "don't redirect stdout and stderr to a window". A wx.Frame is a top-level window. The syntax is wx.Frame(Pare...
%%writefile editor.py #!/usr/bin/env python import wx class MyFrame(wx.Frame): """ We simply derive a new class of Frame. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.Show(...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Status bar & Menu bar Typically, an application has a menu and sometimes a status bar to output messages. Notice the wx.ID_ABOUT and wx.ID_EXIT ids. These are standard ids provided by wxWidgets (see a full list at http://docs.wxwidgets.org/2.8.12/wx_stdevtid.html). It is a good habit to use the standard ID if there is ...
%%writefile editor.py #!/usr/bin/env python import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.CreateStatusBar() # A Statusbar in the bottom of the...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Event handling Reacting to events in wxPython is called event handling. An event is when "something" happens on your application (a button click, text input, mouse movement, etc). Much of GUI programming consists of responding to events. You bind an object to an event using the Bind() method: python class MainWindow(wx...
%%writefile editor.py #!/usr/bin/env python import os import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.CreateStatusBar() # A StatusBar in the b...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Dialogs Of course an editor is useless if it is not able to save or open documents. That's where Common dialogs come in. Common dialogs are those offered by the underlying platform so that your application will look exactly like a native application. Here is the implementation of the OnOpen method in MainWindow: python...
%%writefile editor.py #!/usr/bin/env python import os import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.CreateStatusBar() # A StatusBar in the b...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Working with Windows In this section, we are going to present the way wxPython deals with windows and their contents, including building input forms and using various widgets/controls. We are going to build a small application that calculates the price of a quote. Laying out Visual Elements Within a frame, you'll use ...
%%writefile sizer_demo.py #!/usr/bin/env python import wx import os class MainWindow(wx.Frame): def __init__(self, parent, title): self.dirname='' # A "-1" in the size parameter instructs wxWidgets to use the default size. # In this case, we select 200px width and the default height. ...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
The sizer.Add method has three arguments. The first one specifies the control to include in the sizer. The second one is a weight factor which means that this control will be sized in proportion to other ones. For example, if you had three edit controls and you wanted them to have the proportions 3:2:1 then you would s...
%%writefile example.py import wx class ExamplePanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.quote = wx.StaticText(self, label="Your quote :", pos=(20, 30)) # A multiline TextCtrl - This is here to show how the events wo...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
The notebook Sometimes, a form grows too big to fit on a single page. The wx.Notebook is used in that kind of case : It allows the user to navigate quickly between a small amount of pages by clicking on associated tabs. We implement this by putting the wx.Notebook instead of our form into the main Frame and then add ou...
%%writefile notebook_demo.py import wx from example import ExamplePanel app = wx.App(False) frame = wx.Frame(None, title="Demo with Notebook",size=(500,400)) nb = wx.Notebook(frame) nb.AddPage(ExamplePanel(nb), "Absolute Positioning") nb.AddPage(ExamplePanel(nb), "Page Two") nb.AddPage(ExamplePanel(nb), "Page Three")...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Improving the layout - using Sizers Using absolute positioning is often not very satisfying: The result is ugly if the windows are not (for one reason or another) the right size. WxPython has very rich vocabulary of objects to lay out controls. - wx.BoxSizer is the most common and simple layout object but it permits a ...
%%writefile example.py import wx class ExamplePanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # create some sizers mainSizer = wx.BoxSizer(wx.VERTICAL) grid = wx.GridBagSizer(hgap=5, vgap=5) hSizer = wx.BoxSizer(wx.HORIZONTAL) self.quote...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
wxpython and matplotlib To use matplotlib to plot or show images in a panel, we rely on the matplotlib library.
%%writefile mpl_demo.py #!/usr/bin/env python #import wxversion #wxversion.ensureMinimal('2.8') from numpy import arange, sin, pi from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure import wx class CanvasFrame(wx.Frame): def __init__(self): ...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Let's see how this works. python self.figure = Figure() initializes the top level container for all plot elements. Everything in the plot goes within this object, just like everything in our wx application goes into our frame! python self.axes = self.figure.add_subplot(111) Our figure can contain many subplots, but her...
%%writefile mpl_demo.py #!/usr/bin/env python import wxversion wxversion.ensureMinimal('2.8') from numpy import arange, sin, pi from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigureCanvas, \ NavigationToolbar2WxAgg as NavigationToolbar from matplotlib.figure import Figure import wx class...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
It is possible to use this navigation toolbar as a starting point to add more buttons and capabilities. This is another example from the matplotlib demo library.
%%writefile mpl_demo.py #!/usr/bin/env python import wxversion wxversion.ensureMinimal('2.8') from numpy import arange, sin, pi from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg from matplotlib.backends.backend_wx impor...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Matplotlib examples We give here a few more examples to show the various capabilities. Buttons
%%writefile buttons_demo.py #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button freqs = np.arange(2, 20, 3) fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(0.0, 1.0, 0.001) s = np.sin(2*np.pi*freqs[0]*t) l, = plt.plot(t, s, lw=2) clas...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Check Buttons
%%writefile checkbuttons_demo.py #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(6*np.pi*t) fig, ax = plt.subplots() l0, = ax.plot(t, s0, visible=False, lw=2) l1...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Cursor
%%writefile cursor_demo.py #!/usr/bin/env python from matplotlib.widgets import Cursor import numpy as np import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, axisbg='#FFFFCC') x, y = 4*(np.random.rand(2, 100) - .5) ax.plot(x, y, 'o') ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) # se...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Rectangle selector
%%writefile rectsel.py #!/usr/bin/env python """ Do a mouseclick somewhere, move the mouse to some destination, release the button. This class gives click- and release-events and also draws a line or a box from the click-point to the actual mouseposition (within the same axes) until the button is released. Within the...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Slider
%%writefile slider_demo.py import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 s = a0*np.sin(2*np.pi*f0*t) l, = plt.plot(t, s, lw=2, color='red') ...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Span selector
%%writefile span_demo.py #!/usr/bin/env python """ The SpanSelector is a mouse widget to select a xmin/xmax range and plot the detail view of the selected region in the lower axes """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import SpanSelector fig = plt.figure(figsize=(8, 6)) ax = fi...
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
Further reading http://t2mh.com/python/wxPython%20in%20Action%20(2006).pdf https://www.tutorialspoint.com/wxpython/wxpython_tutorial.pdf Versions
%load_ext version_information %version_information wxpython
Lecture-widgets.ipynb
darioflute/CS4A
gpl-3.0
A lot of the following code is taken from or inspired by this excellent <a href = "http://brandonrose.org/clustering", target="_blank">Document Clustering</a> tutorial
from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(use_idf=True, ngram_range =(1,3)) train_data_features = vectorizer.fit_transform(clean_tweets) terms = vectorizer.get_feature_names() from sklearn.cluster import KMeans num_clusters = 15 km = KMeans(n_clusters=num_clusters) k...
#vinb - Cluster Tweets.ipynb
maniacalbrain/Cluster-vinb-tweets
mit
With no ngrams_range set (default of 1) there was a tendency for an "uber-cluster" to appear. Even at 30 clusters one of them contained over 33% of the tweets. However, the tweets in the other clusters seemed to be very strongly correlated. In the above, with ngrams_range set to (1, 3) the important words seems a lot b...
for i in range(num_clusters): print("Cluster %d words:" % i, end='') for ind in order_centroids[i, :5]: print(' %s' % terms[ind], end=',') print() for text in pd.DataFrame(clustered_debate.Text[clustered_debate.cluster == i]).Text.head(10): print(text) print() print()
#vinb - Cluster Tweets.ipynb
maniacalbrain/Cluster-vinb-tweets
mit
In the following block change the number on the first row to that of the cluster you want and change the number on the second row to the number of tweets from that cluster that you want. The below example prints out 10 tweets from cluster0
display = pd.DataFrame(clustered_debate.Text[clustered_debate.cluster == 0]) for text in display.Text.head(10): print(text)
#vinb - Cluster Tweets.ipynb
maniacalbrain/Cluster-vinb-tweets
mit
We can plot these points on a scatterplot. In the following, a + means "Rain" and a - is "Sun" (no rain). Classification is defined as the task of predicting the correct label or category of an unknown point. With two classes, we divide the data space into two halves, one for each class. So when we receive a new point...
import numpy as np from sklearn.datasets import load_iris # load iris and grab our data and labels iris = load_iris() labels, data = iris.target, iris.data num_samples = len(labels) # size of our dataset num_features = len(iris.feature_names) # number of columns/variables # shuffle the dataset shuffle_order = np.r...
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
Let's view a table showing the first 20 samples.
label_names = np.array([iris.target_names[l] for l in labels]) table_labels = np.array(['class']+iris.feature_names).reshape((1, 1+num_features)) class_names = iris.target_names table_data = np.concatenate([np.array(label_names).reshape(num_samples, 1), data], axis=1)[0:20] # display table table_full = np.concatenate(...
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
For simplicity, we will restrict our attention to just the first two features, sepal width and sepal length. Let's plot the dataset.
# plot the original data x, y, lab = data[:, 0], data[:, 1], labels plt.figure(figsize=(8, 6)) plt.scatter(x, y, c=lab) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.title('Iris dataset')
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
Suppose we are given a new point whose sepal length (x) and sepal width (y) are the following:
new_x, new_y = 6.5, 3.7
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
Let's plot it on the graph. What could its class be?
# plot the original data x, y, lab = data[:, 0], data[:, 1], labels plt.figure(figsize=(8, 6)) plt.scatter(x, y, c=lab) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.title('Iris dataset') # put the new point on top plt.scatter(new_x, new_y, c='grey', cmap=None, edgecolor='k') plt.annotate('?', (new_x+0.45,...
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
Our simple approach to predicting the new point's label is to find the point in the dataset which is closest to the new point, and copying its label.
# calculate the distance between the new point and each of the points in our labeled dataset distances = np.sum((data[:,0:2] - [new_x, new_y])**2, axis=1) # find the index of the point whose distance is lowest closest_point = np.argmin(distances) # take its label new_label = labels[closest_point] print('Predicted la...
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
That's it! That is k-nearest neighbors where we set k = 1. If k &gt; 1, we find the k closest points and take a vote among them. We can now plot the newly-labeled point on top of the dataset.
# append the newly labeled point in our dataset x = np.append(x, new_x) y = np.append(y, new_y) lab = np.append(lab, new_label) # scatter plot as before plt.figure(figsize=(8, 6)) plt.scatter(x, y, c=lab) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.title('Iris dataset') plt.annotate("", xytext=(x[closest_...
examples/fundamentals/classification_kNN.ipynb
ml4a/ml4a-guides
gpl-2.0
1. Load the LAS file with lasio
import lasio l = lasio.read('../data/P-129.LAS') # Line 1.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
That's it! But the object itself doesn't tell us much — it's really just a container:
l
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
2. Look at the WELL section of the header
l.header['Well'] # Line 2.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
You can go in and find the KB if you know what to look for:
l.header['Parameter']['EKB']
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
3. Look at the curve data The curves are all present one big NumPy array:
l.data
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
Or we can go after a single curve object:
l.curves.GR # Line 3.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
And there's a shortcut to its data:
l['GR'] # Line 4.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
...so it's easy to make a plot against depth:
import matplotlib.pyplot as plt plt.figure(figsize=(15,3)) plt.plot(l['DEPT'], l['GR']) plt.show()
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
4. Inspect the curves as a pandas dataframe
l.df().head() # Line 5.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
5. Load the LAS file with welly
from welly import Well w = Well.from_las('../data/P-129.LAS') # Line 6.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
welly Wells know how to display some basics:
w
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
And the Well object also has lasio's access to a pandas DataFrame:
w.df().head()
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
6. Look at welly's Curve object Like the Well, a Curve object can report a bit about itself:
gr = w.data['GR'] # Line 7. gr
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
One important thing about Curves is that each one knows its own depths — they are stored as a property called basis. (It's not actually stored, but computed on demand from the start depth, the sample interval (which must be constant for the whole curve) and the number of samples in the object.)
gr.basis
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
7. Plot part of a curve We'll grab the interval from 300 m to 1000 m and plot it.
gr.to_basis(start=300, stop=1000).plot() # Line 8.
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
8. Smooth a curve Curve objects are, fundamentally, NumPy arrays. But they have some extra tricks. We've already seen Curve.plot(). Using the Curve.smooth() method, we can easily smooth a curve, eg by 15 m (passing samples=True would smooth by 15 samples):
sm = gr.smooth(window_length=15, samples=False) # Line 9. sm.plot()
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
9. Export a set of curves as a matrix You can get at all the data through the lasio l.data object:
print("Data shape: {}".format(w.las.data.shape)) w.las.data
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
But we might want to do some other things, such as specify which curves you want (optionally using aliases like GR1, GRC, NGC, etc for GR), resample the data, or specify a start and stop depth — welly can do all this stuff. This method is also wrapped by Project.data_as_matrix() which is nice because it ensures that al...
w.data.keys() keys=['CALI', 'DT', 'DTS', 'RHOB', 'SP'] w.plot(tracks=['TVD']+keys) X, basis = w.data_as_matrix(keys=keys, start=275, stop=1850, step=0.5, return_basis=True) w.data['CALI'].shape
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
So CALI had 12,718 points in it... since we downsampled to 0.5 m and removed the top and tail, we should have substantially fewer points:
X.shape plt.figure(figsize=(15,3)) plt.plot(X.T[0]) plt.show()
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
10+. BONUS: fix the lat, lon OK, we're definitely going to go over our budget on this one. Did you notice that the location of the well did not get loaded properly?
w.location
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
Let's look at some of the header: # LAS format log file from PETREL # Project units are specified as depth units #================================================================== ~Version information VERS. 2.0: WRAP. YES: #================================================================== ~WELL INFORMATION #MNEM....
import re def transform_ll(text): """ Parses malformed lat and lon so they load properly. """ def callback(match): d = match.group(1).strip() m = match.group(2).strip() s = match.group(3).strip() c = match.group(4).strip() if c.lower() in ('w', 's') and d[0] != '...
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
Make sure that works!
print(transform_ll("""Lat = 45* 12' 34.237" N""")) remap = { 'LATI': 'LOC', # Use LOC for the parameter LATI. 'LONG': 'UWI', # Use UWI for the parameter LONG. 'LOC': None, # Use nothing for the parameter SECT. 'SECT': None, # Use nothing for the parameter SECT. 'RANG': None, # Use nothing ...
notebooks/08_Read_and_write_LAS.ipynb
agile-geoscience/xlines
apache-2.0
数据理解
data_train.info()
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
上面的数据说啥了?它告诉我们,训练数据中总共有891名乘客,但是很不幸,我们有些属性的数据不全,比如说: - Age(年龄)属性只有714名乘客有记录 - Cabin(客舱)更是只有204名乘客是已知的 似乎信息略少啊,想再瞄一眼具体数据数值情况呢?恩,我们用下列的方法,得到数值型数据的一些分布(因为有些属性,比如姓名,是文本型;而另外一些属性,比如登船港口,是类目型。这些我们用下面的函数是看不到的):
data_train.describe()
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
我们从上面看到更进一步的什么信息呢? mean字段告诉我们,大概0.383838的人最后获救了,2/3等舱的人数比1等舱要多,平均乘客年龄大概是29.7岁(计算这个时候会略掉无记录的)等等… 这个时候我们可能会有一些想法了: - 不同舱位/乘客等级可能和财富/地位有关系,最后获救概率可能会不一样 - 年龄对获救概率也一定是有影响的,毕竟前面说了,副船长还说『小孩和女士先走』呢 - 和登船港口是不是有关系呢?也许登船港口不同,人的出身地位不同? 口说无凭,空想无益。老老实实再来统计统计,看看这些属性值的统计分布吧。
plt.figure(figsize=(12,8)) plt.subplot(2,3,1) sns.countplot(x='Pclass',hue='Survived',data=data_train) plt.title('Pclass vs Survived') plt.subplot(2,3,2) sns.countplot(x='Sex',hue='Survived',data=data_train) plt.title('Sex vs Survived') plt.subplot(2,3,3) sns.countplot(x='Embarked',hue='Survived',data=data_train) plt...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
结论: - 钱和地位对舱位有影响,进而对获救的可能性也有影响 - 很尊重lady,lady first践行得不错。性别无疑也要作为重要特征加入最后的模型之中 - 登船港口居然是有影响的 - 单身一个人,获救的可能性还是比较低的
fig = plt.figure() fig.set(alpha=0.2) data_train.Age[data_train.Survived == 0].plot(kind='kde') data_train.Age[data_train.Survived == 1].plot(kind='kde') #ticket是船票编号,应该是unique的,和最后的结果没有太大的关系,先不纳入考虑的特征范畴把 #cabin只有204个乘客有值,我们先看看它的一个分布 data_train.Cabin.value_counts()
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
Cabin这鬼属性,应该算作类目型的,本来缺失值就多,还如此不集中,注定是个棘手货…第一感觉,这玩意儿如果直接按照类目特征处理的话,太散了,估计每个因子化后的特征都拿不到什么权重。-----> 找技术人员去了解什么含义。。。 为方便,我们以Un表示没有的情况 数据预处理与转化
data_train = pd.read_csv("../kaggle_titanic/data/train.csv",index_col='PassengerId') data_test = pd.read_csv("../kaggle_titanic/data/test.csv",index_col='PassengerId') data = pd.concat([data_train, data_test],axis=0) data.info()
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
缺失值处理
data.Embarked[data.Embarked.isnull()] = data.Embarked.dropna().mode().values data.groupby(data.Pclass).mean()['Fare'] data.Fare[data.Fare.isnull()] = 13.302889 from sklearn.ensemble import RandomForestRegressor age_df = data[['Age','Fare', 'Parch', 'SibSp', 'Pclass']] # 乘客分成已知年龄和未知年龄两部分 known_age = age_df[age_df.Age...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
建模
from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.feature_selection import SelectKBest from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV import sklearn.externals.jo...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
提交模型,在测试集上的准确率为76.6%, 排名2700++
# 保存模型 joblib.dump(lr, '../kaggle_titanic/model/lr.ckpt') # lr_read = joblib.load('../kaggle_titanic/model/lr.ckpt')
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
改进
import cPickle with open("../kaggle_titanic/data/train_data","rb") as f: X_train, y_train = cPickle.load(f) # 因为没有测试集,我们使用KFold来评估模型的有效性 lr = LogisticRegression() score = cross_val_score(lr,X_train,y_train,cv=5) score.mean() # 我们使用sklearn选择特征 from sklearn.feature_selection import SelectKBest skb = SelectKBest(k=...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
特征选择无益于效果的提升,可能是因为特征本身比较少,相关性都比较强。 如果在文件分类中,特征数据多达百万,这时进行特征选择,是很必要的。
# 流水线 + 优化 clf = Pipeline([('skb',SelectKBest(k=100)),('lr',LogisticRegression(C=1))]) grid_param = {'skb__k':[8,9,10,11,12,13,14], 'lr__C':[0.01, 0.1, 1, 10, 100], 'lr__penalty':['l1','l2']} grid = GridSearchCV(clf, grid_param, n_jobs=-1, cv=5) grid.fit(X_train,y_train) print grid.best_...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
提交结果,得分为0.78,排名2000+。
# 学习曲线 from sklearn.model_selection import learning_curve pp = Pipeline([('skb',SelectKBest(k=14)),('lr',LogisticRegression(C=0.1))]) train_sizes, train_scores, test_scores = learning_curve(pp, X_train, y_train, cv=5, n_jobs=-1, train_sizes=np.linspace(0.2, 1.0, 20)) train_scores_mean = np.mean(train_scores, axis=1) ...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
改进2
from sklearn.model_selection import train_test_split X_tra, X_val, y_tra, y_val = train_test_split(X_train,y_train, test_size=0.3, random_state=0) lrl1 = LogisticRegression(C=1.0, penalty="l1", tol=1e-6) lrl1.fit(X_tra, y_tra) y_val_pred = lrl1.predict(X_val) val_pid_set = X_val.iloc[y_val.tolist() != y_val_pred,:]....
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
我们随便列一些可能可以做的优化操作: * Age属性不使用现在的拟合方式,而是根据名称中的『Mr』『Mrs』『Miss』等的平均值进行填充。 * Age不做成一个连续值属性,而是使用一个步长进行离散化,变成离散的类目feature。 * Cabin再细化一些,对于有记录的Cabin属性,我们将其分为前面的字母部分(我猜是位置和船层之类的信息) 和 后面的数字部分(应该是房间号,有意思的事情是,如果你仔细看看原始数据,你会发现,这个值大的情况下,似乎获救的可能性高一些)。 * Pclass和Sex俩太重要了,我们试着用它们去组出一个组合属性来试试,这也是另外一种程度的细化。 * 单加一个Child字段,Age<=12的,设为...
from sklearn.ensemble import BaggingClassifier clf = LogisticRegression(C=1.0, penalty="l1", tol=1e-6) bag_clf = BaggingClassifier(clf, n_estimators=20, max_samples=0.75, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=-1) bag_clf.fit(X_train, y_train) bag_clf.score(X_train, y_train) scores = cross...
sklearn_titanic.ipynb
gengyj/ml-basic-course
gpl-3.0
One single point at a time, define the error between the true label and the model's prediction of the label
total_error = 0.0 for x,y in zip(xs, ys): y_model = m*x + b # the predicted model output; often called y_hat, but we'll use that later in notebook total_error += (y-y_model)**2 # sum of squared error between true and predicted y; the "cost" to be minimized
notebooks/point_by_point_intro_to_tensorflow.ipynb
the-deep-learners/TensorFlow-LiveLessons
mit
Define optimizer as SSE-minimizing gradient descent
optimizer_operation = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(total_error) # illustrate learning rate too high: # optimizer_operation = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(total_error) # optimizer_operation = tf.train.GradientDescentOptimizer(learning_rate=0.1).mini...
notebooks/point_by_point_intro_to_tensorflow.ipynb
the-deep-learners/TensorFlow-LiveLessons
mit
With the computational graph designed, we initialize a session to execute it
with tf.Session() as session: session.run(initializer_operation) n_epochs = 1000 # run notebook through with 10, then run again with 1000 for iteration in range(n_epochs): session.run(optimizer_operation) # this line executes the graph once, taking a single step toward minimizing cost ...
notebooks/point_by_point_intro_to_tensorflow.ipynb
the-deep-learners/TensorFlow-LiveLessons
mit
Generating the data We use the make_moons method from scikit-learn, which allows to generate directly a set of points and the associated labels.
from sklearn.datasets import make_moons X, y = make_moons(n_samples=100, noise=0.2) colz = {0: 'dodgerblue', 1:"goldenrod"} for pt, cl in zip(X, y): plt.scatter(pt[0],pt[1], color=colz[cl]) plt.scatter([], [], color='dodgerblue', label='0') plt.scatter([], [], color='goldenrod', label='1') plt.legend()
notebooks/chap_2_knn.ipynb
hrjn/ISLR_reading_group
gpl-3.0
Writing the KNN function
def knn(pt, X, y, k): """ Returns the class predicted for pt using the knn algorithm """ dists = [] # Put features and outputs in the same array: data = np.stack((X[:,0], X[:,1], y), axis=1) # Compute the distance between pt and all the data points: dists = [euclidean(pt, [data_pt[0...
notebooks/chap_2_knn.ipynb
hrjn/ISLR_reading_group
gpl-3.0
Applying the KNN function to the moons dataset
# Create the grid: resolution = 0.05 x1_min = min(X[:,0]) - 0.5 x1_max = max(X[:,0]) + 0.5 x2_min = min(X[:,1]) - 0.5 x2_max = max(X[:,1]) + 0.5 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\ np.arange(x2_min, x2_max, resolution)) pts_domain = np.stack((np.ravel(xx1), np.ravel(xx2...
notebooks/chap_2_knn.ipynb
hrjn/ISLR_reading_group
gpl-3.0