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
Introduction Dust in the interstellar medium (ISM) extinguishes background starlight. The wavelength dependence of the extinction is such that short-wavelength light is extinguished more than long-wavelength light, and we call this effect *reddening*.If you're new to extinction, here is a brief introduction to the ty...
# Create wavelengths array. wav = np.arange(0.1, 3.0, 0.001)*u.micron for model in [CCM89, F99]: for R in (2.0,3.0,4.0): # Initialize the extinction model ext = model(Rv=R) plt.plot(1/wav, ext(wav), label=model.name+' R='+str(R)) plt.xlabel('$\lambda^{-1}$ ($\mu$m$^{-1}$)') plt.yla...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Astronomers studying the ISM often display extinction curves against inverse wavelength (wavenumber) to show the ultraviolet variation, as we do here. Infrared extinction varies much less and approaches zero at long wavelength in the absence of wavelength-independent, or grey, extinction. Example 2: Deredden a Spectr...
download_dir = pathlib.Path('~/.astropy/cache/astroquery/Mast').expanduser() download_dir.mkdir(exist_ok=True) obsTable = Observations.query_object("HD 147933", radius="1 arcsec") obsTable_spec = obsTable[obsTable['dataproduct_type'] == 'spectrum'] obsTable_spec obsids = obsTable_spec[39]['obsid'] dataProductsByID = O...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
We read the downloaded files into an astropy table:
t_lwr = Table.read(download_dir / 'mastDownload/IUE/lwr05639/lwr05639mxlo_vo.fits') print(t_lwr)
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
The `.quantity` extension in the next lines will read the Table columns into Quantity vectors. Quantities keep the units of the Table column attached to the numpy array values.
wav_UV = t_lwr['WAVE'][0,].quantity UVflux = t_lwr['FLUX'][0,].quantity
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Now, we use astroquery again to fetch photometry from Simbad to go with the IUE spectrum:
custom_query = Simbad() custom_query.add_votable_fields('fluxdata(U)','fluxdata(B)','fluxdata(V)') phot_table=custom_query.query_object('HD 147933') Umag=phot_table['FLUX_U'] Bmag=phot_table['FLUX_B'] Vmag=phot_table['FLUX_V']
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
To convert the photometry to flux, we look up some [properties of the photometric passbands](http://ned.ipac.caltech.edu/help/photoband.lst), including the flux of a magnitude zero star through the each passband, also known as the zero-point of the passband.
wav_U = 0.3660 * u.micron zeroflux_U_nu = 1.81E-23 * u.Watt/(u.m*u.m*u.Hz) wav_B = 0.4400 * u.micron zeroflux_B_nu = 4.26E-23 * u.Watt/(u.m*u.m*u.Hz) wav_V = 0.5530 * u.micron zeroflux_V_nu = 3.64E-23 * u.Watt/(u.m*u.m*u.Hz)
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
The zero-points that we found for the optical passbands are not in the same units as the IUE fluxes. To make matters worse, the zero-point fluxes are $F_\nu$ and the IUE fluxes are $F_\lambda$. To convert between them, the wavelength is needed. Fortunately, astropy provides an easy way to make the conversion with *e...
zeroflux_U = zeroflux_U_nu.to(u.erg/u.AA/u.cm/u.cm/u.s, equivalencies=u.spectral_density(wav_U)) zeroflux_B = zeroflux_B_nu.to(u.erg/u.AA/u.cm/u.cm/u.s, equivalencies=u.spectral_density(wav_B)) zeroflux_V = zeroflux_V_nu.to(u.erg/u.AA/u.cm/u.cm/u.s, ...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Now we can convert from photometry to flux using the definition of magnitude:$$F=F_0\ 10^{-0.4\, m}$$
Uflux = zeroflux_U * 10.**(-0.4*Umag) Bflux = zeroflux_B * 10.**(-0.4*Bmag) Vflux = zeroflux_V * 10.**(-0.4*Vmag)
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Using astropy quantities allow us to take advantage of astropy's unit support in plotting. [Calling `astropy.visualization.quantity_support` explicitly turns the feature on.](http://docs.astropy.org/en/stable/units/quantity.htmlplotting-quantities) Then, when quantity objects are passed to matplotlib plotting function...
astropy.visualization.quantity_support() plt.plot(wav_UV,UVflux,'m',label='UV') plt.plot(wav_V,Vflux,'ko',label='U, B, V') plt.plot(wav_B,Bflux,'ko') plt.plot(wav_U,Uflux,'ko') plt.legend(loc='best') plt.ylim(0,3E-10) plt.title('rho Oph') plt.show()
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Finally, we initialize the extinction model, choosing values $R_V = 5$ and $E_{B-V} = 0.5$. This star is famous in the ISM community for having large-$R_V$ dust in the line of sight.
Rv = 5.0 # Usually around 3, but about 5 for this star. Ebv = 0.5 ext = F99(Rv=Rv)
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
To extinguish (redden) a spectrum, multiply by the `ext.extinguish` function. To unextinguish (deredden), divide by the same `ext.extinguish`, as we do here:
plt.semilogy(wav_UV,UVflux,'m',label='UV') plt.semilogy(wav_V,Vflux,'ko',label='U, B, V') plt.semilogy(wav_B,Bflux,'ko') plt.semilogy(wav_U,Uflux,'ko') plt.semilogy(wav_UV,UVflux/ext.extinguish(wav_UV,Ebv=Ebv),'b', label='dereddened: EBV=0.5, RV=5') plt.semilogy(wav_V,Vflux/ext.extinguish(wav_V,Ebv=Ebv),'...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Notice that, by dereddening the spectrum, the absorption feature at 2175 Angstrom is removed. This feature can also be seen as the prominent bump in the extinction curves in Example 1. That we have smoothly removed the 2175 Angstrom feature suggests that the values we chose, $R_V = 5$ and $E_{B-V} = 0.5$, are a reaso...
# Optional, for when the STScI ftp server is not answering: config.conf.vega_file = 'http://ssb.stsci.edu/cdbs/calspec/alpha_lyr_stis_008.fits' config.conf.johnson_u_file = 'http://ssb.stsci.edu/cdbs/comp/nonhst/johnson_u_004_syn.fits' config.conf.johnson_b_file = 'http://ssb.stsci.edu/cdbs/comp/nonhst/johnson_b_004_sy...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
If you are running this with your own python, see the [synphot documentation](https://synphot.readthedocs.io/en/latest/installation-and-setup) on how to install your own copy of the necessary files. Next, let's make a background flux to which we will apply extinction. Here we make a 10,000 K blackbody using the model ...
# First, create a blackbody at some temperature. sp = SourceSpectrum(BlackBodyNorm1D, temperature=10000) # sp.plot(left=1, right=15000, flux_unit='flam', title='Blackbody') # Get the Vega spectrum as the zero point flux. vega = SourceSpectrum.from_vega() # vega.plot(left=1, right=15000) # Normalize the blackbody to s...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Now we initialize the extinction model and choose an extinction of $A_V$ = 2. To get the `dust_extinction` model working with `synphot`, we create a wavelength array and make a spectral element with the extinction model as a lookup table.
# Initialize the extinction model and choose the extinction, here Av = 2. ext = CCM89(Rv=3.1) Av = 2. # Create a wavelength array. wav = np.arange(0.1, 3, 0.001)*u.micron # Make the extinction model in synphot using a lookup table. ex = ExtinctionCurve(ExtinctionModel1D, points=wav, lookup_tabl...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Synthetic photometry refers to modeling an observation of a star by multiplying the theoretical model for the astronomical flux through a certain filter response function, then integrating.
# "Observe" the star through the filter and integrate to get photometric mag. sp_obs = Observation(sp_ext, v_band) sp_obs_before = Observation(sp_norm, v_band) # sp_obs.plot(left=1, right=15000, flux_unit='flam', # title='Normed Blackbody with Extinction through V Filter')
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
Next, `synphot` performs the integration and computes magnitudes in the Vega system.
sp_stim_before = sp_obs_before.effstim(flux_unit='vegamag', vegaspec=vega) sp_stim = sp_obs.effstim(flux_unit='vegamag', vegaspec=vega) print('before dust, V =', np.round(sp_stim_before,1)) print('after dust, V =', np.round(sp_stim,1)) # Calculate extinction and compare to our chosen value. Av_calc = sp_stim - sp_stim...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
This is a good check for us to do. We normalized our spectrum to $V$ = 10 mag and added 2 mag of visual extinction, so the synthetic photometry procedure should reproduce these chosen values, and it does. Now we are ready to find the extinction in other passbands. We calculate the new photometry for the rest of the ...
bands = [u_band,b_band,v_band,r_band,i_band,j_band,h_band,k_band] for band in bands: # Calculate photometry with dust: sp_obs = Observation(sp_ext, band, force='extrap') obs_effstim = sp_obs.effstim(flux_unit='vegamag', vegaspec=vega) # Calculate photometry without dust: sp_obs_i = Observation(sp_n...
_____no_output_____
BSD-3-Clause
tutorials/color-excess/color-excess.ipynb
jvictor42/astropy-tutorials
2D ERT modeling and inversion
import matplotlib.pyplot as plt import numpy as np import pygimli as pg import pygimli.meshtools as mt from pygimli.physics import ert
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Create geometry definition for the modelling domain.worldMarker=True indicates the default boundary conditions for the ERT
world = mt.createWorld(start=[-50, 0], end=[50, -50], layers=[-1, -8], worldMarker=True)
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Create some heterogeneous circular anomaly
block = mt.createCircle(pos=[-4.0, -5.0], radius=[1, 1.8], marker=4, boundaryMarker=10, area=0.01) circle = mt.createCircle(pos=[4.0, -5.0], radius=[1, 1.8], marker=5, boundaryMarker=10, area=0.01) poly = mt.createPolygon([(1,-4), (2,-1.5), (4,-2), (5,-2), ...
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Merge geometry definition into a Piecewise Linear Complex (PLC)
geom = world + block + circle # + poly
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Optional: show the geometry
pg.show(geom)
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Create a Dipole Dipole ('dd') measuring scheme with 21 electrodes.
scheme = ert.createData(elecs=np.linspace(start=-20, stop=20, num=42), schemeName='dd')
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Put all electrode (aka sensors) positions into the PLC to enforce meshrefinement. Due to experience, its convenient to add further refinementnodes in a distance of 10% of electrode spacing to achieve sufficientnumerical accuracy.
for p in scheme.sensors(): geom.createNode(p) geom.createNode(p - [0, 0.01]) # Create a mesh for the finite element modelling with appropriate mesh quality. mesh = mt.createMesh(geom, quality=34) # Create a map to set resistivity values in the appropriate regions # [[regionNumber, resistivity], [regionNumber,...
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Perform the modeling with the mesh and the measuring scheme itselfand return a data container with apparent resistivity values,geometric factors and estimated data errors specified by the noise setting.The noise is also added to the data. Here 1% plus 1µV.Note, we force a specific noise seed as we want reproducable res...
data = ert.simulate(mesh, scheme=scheme, res=rhomap, noiseLevel=1, noiseAbs=1e-6, seed=1337, verbose=False) pg.info(np.linalg.norm(data['err']), np.linalg.norm(data['rhoa'])) pg.info('Simulated data', data) pg.info('The data contains:', data.dataMap().keys()) pg.info('Simulated rhoa (min/max)', mi...
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Optional: you can filter all values and tokens in the data container.Its possible that there are some negative data values due to noise andhuge geometric factors. So we need to remove them.
data.remove(data['rhoa'] < 0) # data.remove(data['k'] < -20000.0) pg.info('Filtered rhoa (min/max)', min(data['rhoa']), max(data['rhoa'])) # You can save the data for further use data.save('simple.dat') # You can take a look at the data ert.show(data, cMap="RdBu_r")
24/11/21 - 13:43:27 - pyGIMLi - INFO - Filtered rhoa (min/max) 44.872181820362094 55.08720265284357
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Initialize the ERTManager, e.g. with a data container or a filename.
mgr = ert.ERTManager('simple.dat')
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Run the inversion with the preset data. The Inversion mesh will be createdwith default settings.
inv = mgr.invert(lam=10, verbose=False) #np.testing.assert_approx_equal(mgr.inv.chi2(), 0.7, significant=1)
24/11/21 - 13:41:23 - pyGIMLi - INFO - Found 2 regions. 24/11/21 - 13:41:23 - pyGIMLi - INFO - Region with smallest marker (1) set to background 24/11/21 - 13:41:23 - pyGIMLi - INFO - Creating forward mesh from region infos. 24/11/21 - 13:41:23 - Core - WARNING - ...
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
Let the ERTManger show you the model of the last successful run and how itfits the data. Shows data, model response, and model.
mgr.showResultAndFit(cMap="RdBu_r") meshPD = pg.Mesh(mgr.paraDomain) # Save copy of para mesh for plotting later
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
You can also provide your own mesh (e.g., a structured grid if you like them)Note, that x and y coordinates needs to be in ascending order to ensure thatall the cells in the grid have the correct orientation, i.e., all cells needto be numbered counter-clockwise and the boundary normal directions need topoint outside.
inversionDomain = pg.createGrid(x=np.linspace(start=-21, stop=21, num=43), y=-pg.cat([0], pg.utils.grange(0.5, 8, n=8))[::-1], marker=2)
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
The inversion domain for ERT problems needs a boundary that represents thefar regions in the subsurface of the halfspace.Give a cell marker lower than the marker for the inversion region, the lowestcell marker in the mesh will be the inversion boundary region by default.
grid = pg.meshtools.appendTriangleBoundary(inversionDomain, marker=1, xbound=50, ybound=50) pg.show(grid, markers=True) #pg.show(grid, markers=True)
_____no_output_____
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
The Inversion can be called with data and mesh as argument as well
model = mgr.invert(data, mesh=grid, lam=10, verbose=False) # np.testing.assert_approx_equal(mgr.inv.chi2(), 0.951027, significant=3)
24/11/21 - 13:41:27 - pyGIMLi - INFO - Found 2 regions. 24/11/21 - 13:41:27 - pyGIMLi - INFO - Region with smallest marker (1) set to background 24/11/21 - 13:41:27 - pyGIMLi - INFO - Creating forward mesh from region infos. 24/11/21 - 13:41:27 - Core - WARNING - ...
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
You can of course get access to mesh and model and plot them for your own.Note that the cells of the parametric domain of your mesh might be ina different order than the values in the model array if regions are used.The manager can help to permutate them into the right order.
# np.testing.assert_approx_equal(mgr.inv.chi2(), 1.4, significant=2) maxC = 150 modelPD = mgr.paraModel(model) # do the mapping pg.show(mgr.paraDomain, modelPD, label='Model', cMap='RdBu_r', logScale=True, cMin=15, cMax=maxC) pg.info('Inversion stopped with chi² = {0:.3}'.format(mgr.fw.chi2())) fig, (ax1, ...
24/11/21 - 13:43:44 - pyGIMLi - INFO - Inversion stopped with chi² = 0.944
CC0-1.0
plot_01_ert_2d_mod_inv.ipynb
ruboerner/pg
N-gram language models or how to write scientific papers (4 pts)We shall train our language model on a corpora of [ArXiv](http://arxiv.org/) articles and see if we can generate a new one!![img](https://media.npr.org/assets/img/2013/12/10/istock-18586699-monkey-computer_brick-16e5064d3378a14e0e4c2da08857efe03c04695e-s8...
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # Alternative manual download link: https://yadi.sk/d/_nGyU2IajjR9-w # !wget "https://www.dropbox.com/s/99az9n1b57qkd9j/arxivData.json.tar.gz?dl=1" -O arxivData.json.tar.gz # !tar -xvzf arxivData.json.tar.gz data = pd.read_json("....
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
TokenizationYou know the dril. The data is messy. Go clean the data. Use WordPunctTokenizer or something.
from nltk.tokenize import WordPunctTokenizer # Task: convert lines (in-place) into strings of space-separated tokens. import & use WordPunctTokenizer tokenizer = WordPunctTokenizer() lines = [' '.join(tokenizer.tokenize(line.lower())) for line in lines] assert sorted(lines, key=len)[0] == \ 'differential contrastiv...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
N-Gram Language Model (1point)A language model is a probabilistic model that estimates text probability: the joint probability of all tokens $w_t$ in text $X$: $P(X) = P(w_1, \dots, w_T)$.It can do so by following the chain rule:$$P(w_1, \dots, w_T) = P(w_1)P(w_2 \mid w_1)\dots P(w_T \mid w_1, \dots, w_{T-1}).$$ The p...
from tqdm import tqdm from collections import defaultdict, Counter # special tokens: # - unk represents absent tokens, # - eos is a special token after the end of sequence UNK, EOS = "_UNK_", "_EOS_" def count_ngrams(lines, n): """ Count how many times each word occured after (n - 1) previous words :pa...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Once we can count N-grams, we can build a probabilistic language model.The simplest way to compute probabilities is in proporiton to counts:$$ P(w_t | prefix) = { Count(prefix, w_t) \over \sum_{\hat w} Count(prefix, \hat w) } $$
class NGramLanguageModel: def __init__(self, lines, n): """ Train a simple count-based language model: compute probabilities P(w_t | prefix) given ngram counts :param n: computes probability of next token given (n - 1) previous words :param lines: an iterable o...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Let's test it!
dummy_lm = NGramLanguageModel(dummy_lines, n=3) p_initial = dummy_lm.get_possible_next_tokens('') # '' -> ['_UNK_', '_UNK_'] assert np.allclose(p_initial['learning'], 0.02) assert np.allclose(p_initial['a'], 0.13) assert np.allclose(p_initial.get('meow', 0), 0) assert np.allclose(sum(p_initial.values()), 1) p_a = dum...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Now that you've got a working n-gram language model, let's see what sequences it can generate. But first, let's train it on the whole dataset.
lm = NGramLanguageModel(lines, n=3)
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
The process of generating sequences is... well, it's sequential. You maintain a list of tokens and iteratively add next token by sampling with probabilities.$ X = [] $__forever:__* $w_{next} \sim P(w_{next} | X)$* $X = concat(X, w_{next})$Instead of sampling with probabilities, one can also try always taking most likel...
def get_next_token(lm, prefix, temperature=1.0): """ return next token after prefix; :param temperature: samples proportionally to lm probabilities ^ (1 / temperature) if temperature == 0, always takes most likely token. Break ties arbitrarily. """ <YOUR CODE> from collections import Counter...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Let's have fun with this model
prefix = 'artificial' # <- your ideas :) for i in range(100): prefix += ' ' + get_next_token(lm, prefix) if prefix.endswith(EOS) or len(lm.get_possible_next_tokens(prefix)) == 0: break print(prefix) prefix = 'bridging the' # <- more of your ideas for i in range(100): prefix += ' ' + get_n...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
__More in the homework:__ nucleous sampling, top-k sampling, beam search(not for the faint of heart). Evaluating language models: perplexity (1point)Perplexity is a measure of how well does your model approximate true probability distribution behind data. __Smaller perplexity = better model__.To compute perplexity on ...
def perplexity(lm, lines, min_logprob=np.log(10 ** -50.)): """ :param lines: a list of strings with space-separated tokens :param min_logprob: if log(P(w | ...)) is smaller than min_logprop, set it equal to min_logrob :returns: corpora-level perplexity - a single scalar number from the formula above ...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Now let's measure the actual perplexity: we'll split the data into train and test and score model on test data only.
from sklearn.model_selection import train_test_split train_lines, test_lines = train_test_split(lines, test_size=0.25, random_state=42) for n in (1, 2, 3): lm = NGramLanguageModel(n=n, lines=train_lines) ppx = perplexity(lm, test_lines) print("N = %i, Perplexity = %.5f" % (n, ppx)) # whoops, it just blew ...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
LM SmoothingThe problem with our simple language model is that whenever it encounters an n-gram it has never seen before, it assigns it with the probabilitiy of 0. Every time this happens, perplexity explodes.To battle this issue, there's a technique called __smoothing__. The core idea is to modify counts in a way tha...
class LaplaceLanguageModel(NGramLanguageModel): """ this code is an example, no need to change anything """ def __init__(self, lines, n, delta=1.0): self.n = n counts = count_ngrams(lines, self.n) self.vocab = set(token for token_counts in counts.values() for token in token_counts) ...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Kneser-Ney smoothing (2 points)Additive smoothing is simple, reasonably good but definitely not a State of The Art algorithm.Your final task in this notebook is to implement [Kneser-Ney](https://en.wikipedia.org/wiki/Kneser%E2%80%93Ney_smoothing) smoothing.It can be computed recurrently, for n>1:$$P_{kn}(w_t | prefix_...
class KneserNeyLanguageModel(NGramLanguageModel): """ A template for Kneser-Ney language model. Default delta may be suboptimal. """ def __init__(self, lines, n, delta=1.0): self.n = n <YOUR CODE> def get_possible_next_tokens(self, prefix): < YOUR CODE > def ge...
_____no_output_____
MIT
week03_lm/seminar.ipynb
ivkrasovskiy/nlp_course
Introduction to matplotlib
import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(0, 10, 50) y = x**2 plt.plot(x,y) plt.title("Title") plt.xlabel("X Label") plt.ylabel("Y Label") plt.subplot(1, 2, 1) plt.plot(x,y, "red") plt.subplot(1,2, 2) plt.plot(y,x, "green") fig = plt.figure() ax = fig.add_axes([0.1, 0.2, 0.9...
_____no_output_____
FTL
notebooks/99_lst_Tests_Mataplotlib.ipynb
lukk60/RETrends
This page was created from a Jupyter notebook. The original notebook can be found [here](https://github.com/klane/databall/blob/master/notebooks/parameter-tuning.ipynb). It investigates tuning model parameters to achieve better performance. First we must import the necessary installed modules.
import itertools import numpy as np import matplotlib.pyplot as plt import seaborn as sns from functools import partial from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from hyperopt...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Next we need to import a few local modules.
import os import sys import warnings warnings.filterwarnings('ignore') module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) from databall.database import Database from databall.plotting import format_538, plot_metrics, plot_matrix from databall.model_sele...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Apply the FiveThirtyEight plot style.
plt.style.use('fivethirtyeight')
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
DataAs before, we collect the stats and betting data from the database and create training and test sets where the 2016 season is reserved as the test set.
database = Database('../data/nba.db') games = database.betting_stats(window=10) x_train, y_train, x_test, y_test = train_test_split(games, 2006, 2016, xlabels=util.stat_names() + ['SEASON'])
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The stats below are the box score stats used during [feature selection](feature-selection.md). I decided to further explore these because they are readily available from multiple sources and do not require any calculation of advanced stats by users.
stats = ['FGM', 'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'OREB', 'DREB', 'AST', 'TOV', 'STL', 'BLK'] stats = ['TEAM_' + s for s in stats] + ['POSSESSIONS'] stats += [s + '_AWAY' for s in stats] + ['HOME_SPREAD']
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Logistic RegressionThe plots below show `LogisticRegression` model performance using different combinations of three parameters in a grid search: `penalty` (type of norm), `class_weight` (where "balanced" indicates weights are inversely proportional to class frequencies and the default is one), and `dual` (flag to use...
# Create functions that return logistic regression models with different parameters models = [partial(LogisticRegression, penalty='l1'), partial(LogisticRegression, penalty='l1', class_weight='balanced'), partial(LogisticRegression), partial(LogisticRegression, class_weight='balanced'), ...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
An alternative solution is to use an optimization algorithm that minimizes a loss function to select the hyperparameters. I experimented with the hyperopt package for this, which accepts a parameter search space and loss function as its inputs. The search space consists of discrete choices and ranges on continuous vari...
space_log = {} space_log['C'] = hp.loguniform('C', -8*np.log(10), -2*np.log(10)) space_log['intercept_scaling'] = hp.loguniform('intercept_scaling', -8*np.log(10), 8*np.log(10)) space_log['penalty'] = hp.choice('penalty', ['l1', 'l2']) space_log['fit_intercept'] = hp.choice('fit_intercept', [False, True]) model = Logis...
{'C': 0.0001943920615336294, 'fit_intercept': True, 'intercept_scaling': 134496.71823111628, 'penalty': 'l2'}
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The search history is displayed below. The intercept scale factor tended toward high values, even though the default value is 1.0.
labels = ['Regularization', 'Intercept Scale', 'Penalty', 'Intercept'] fig, ax = plot_matrix(param_log.index.values, param_log[[k for k in space_log.keys()]].values, 'Iteration', labels, 2, 2, logy=[True, True, False, False]) [a.set_yticks([0, 1]) for a in ax[2:]] ax[2].set_yticklabels(['L1', 'L2...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The cross-validation accuracy history shows that many models performed about the same despite their parameter values given the band of points just below 51% accuracy. The optimizer was also unable to find a model that significantly improved accuracy.
fig = plt.figure(figsize=(12, 6)) plt.plot(param_log.index.values, param_log['accuracy'], '.', markersize=5) title = 'Improvements are hard to come by' subtitle = 'Accuracy of logistic regression hyperparameter optimization history' format_538(fig, 'NBA Stats & Covers.com', xlabel='Iteration', ylabel='Accuracy', ...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Support Vector MachineThe [`LinearSVC`](http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.htmlsklearn.svm.LinearSVC) class is similar to a generic [`SVC`](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.htmlsklearn.svm.SVC) with a linear kernel, but is implemented with liblinear i...
space_svm = {} space_svm['C'] = hp.loguniform('C', -8*np.log(10), -2*np.log(10)) space_svm['intercept_scaling'] = hp.loguniform('intercept_scaling', -8*np.log(10), 8*np.log(10)) space_svm['loss'] = hp.choice('loss', ['hinge', 'squared_hinge']) space_svm['fit_intercept'] = hp.choice('fit_intercept', [False, True]) model...
{'C': 3.2563857398383885e-06, 'fit_intercept': True, 'intercept_scaling': 242.79319791592195, 'loss': 'squared_hinge'}
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The search history below is similar to the logistic regression history, but hyperopt appears to test more intercept scales with low values than before. This is also indicated by the drastic reduction in the intercept scale compared to logistic regression.
labels = ['Regularization', 'Intercept Scale', 'Loss', 'Intercept'] fig, ax = plot_matrix(param_svm.index.values, param_svm[[k for k in space_svm.keys()]].values, 'Iteration', labels, 2, 2, logy=[True, True, False, False]) [a.set_yticks([0, 1]) for a in ax[2:]] ax[2].set_yticklabels(['Hinge', 'Sq...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The plot below shows the `LinearSVC` cross-validation accuracy history. There is a band of points similar to what we observed for logistic regression below 51% accuracy. The support vector machine model does not perform much better than logistic regression, and several points fall below 50% accuracy.
fig = plt.figure(figsize=(12, 6)) plt.plot(param_svm.index.values, param_svm['accuracy'], '.', markersize=5) title = 'Improvements are hard to come by' subtitle = 'Accuracy of support vector machine hyperparameter optimization history' format_538(fig, 'NBA Stats & Covers.com', xlabel='Iteration', ylabel='Accuracy', ...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Random ForestThe code below builds a [`RandomForestClassifier`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.htmlsklearn.ensemble.RandomForestClassifier) hyperparameter search space using the parameters `n_estimators` (number of decision trees in the forest), `class_weight` ...
space_rf = {} space_rf['n_estimators'] = 10 + hp.randint('n_estimators', 40) space_rf['criterion'] = hp.choice('criterion', ['gini', 'entropy']) space_rf['class_weight'] = hp.choice('class_weight', [None, 'balanced']) space_rf['bootstrap'] = hp.choice('bootstrap', [False, True]) model = RandomForestClassifier(random_st...
{'bootstrap': True, 'class_weight': 'balanced', 'criterion': 'entropy', 'n_estimators': 34}
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The random forest hyperparameter search history is displayed below.
labels = ['Estimators', 'Criterion', 'Class Weight', 'Bootstrap'] fig, ax = plot_matrix(param_rf.index.values, param_rf[[k for k in space_rf.keys()]].values, 'Iteration', labels, 2, 2) [a.set_yticks([0, 1]) for a in ax[1:]] ax[1].set_yticklabels(['Gini', 'Entropy']) ax[2].set_yticklabels(['None',...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The cross-validation accuracy history shows the random forest model performs slightly worse than logistic regression.
fig = plt.figure(figsize=(12, 6)) plt.plot(param_rf.index.values, param_rf['accuracy'], '.', markersize=5) title = 'Improvements are hard to come by' subtitle = 'Accuracy of random forest hyperparameter optimization history' format_538(fig, 'NBA Stats & Covers.com', xlabel='Iteration', ylabel='Accuracy', ti...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
Neural NetworkThe code below builds a [`MLPClassifier`](http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.htmlsklearn.neural_network.MLPClassifier) hyperparameter search space using the parameters `hidden_layer_sizes` (number of neurons in each hidden layer), `alpha` (controls the L...
space_mlp = {} space_mlp['hidden_layer_sizes'] = 10 + hp.randint('hidden_layer_sizes', 40) space_mlp['alpha'] = hp.loguniform('alpha', -8*np.log(10), 3*np.log(10)) space_mlp['activation'] = hp.choice('activation', ['relu', 'logistic', 'tanh']) space_mlp['solver'] = hp.choice('solver', ['lbfgs', 'sgd', 'adam']) model = ...
{'activation': 'tanh', 'alpha': 5.700733605522687e-06, 'hidden_layer_sizes': 49, 'solver': 'lbfgs'}
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The multi-layer perceptron hyperparameter search history is displayed below.
labels = ['Hidden Neurons', 'Regularization', 'Activation', 'Solver'] fig, ax = plot_matrix(param_mlp.index.values, param_mlp[[k for k in space_mlp.keys()]].values, 'Iteration', labels, 2, 2, logy=[False, True, False, False]) [a.set_yticks([0, 1, 2]) for a in ax[2:]] ax[2].set_yticklabels(['RELU'...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
The cross-validation history suggests the multi-layer perceptron performs the best of the four models, albeit the improvement is minor.
fig = plt.figure(figsize=(12, 6)) plt.plot(param_mlp.index.values, param_mlp['accuracy'], '.', markersize=5) title = 'Improvements are hard to come by' subtitle = 'Accuracy of multi-layer perceptron hyperparameter optimization history' format_538(fig, 'NBA Stats & Covers.com', xlabel='Iteration', ylabel='Accuracy', ...
_____no_output_____
MIT
notebooks/parameter-tuning.ipynb
klane/nba
CollationAn alternative for `sorted()` using `icu.Collator` and `icu.RuleBasedCollator`. Currently supports lists, tuples, strings, dataframes and series.Custom collation rules are defined for Dinka and Akan.All icu::Collator supported locales are available.__TODO:__* add support for numpy arrays* add support for dict...
import pandas as pd import el_collation as elcol import random
_____no_output_____
MIT
collation/el_collation.ipynb
enabling-languages/dinka
Custom Collation Rules (unsupported locales)The following examples will be using predefined collation rules for Dinka.
# Set language lang = "din-SS" # Provide Dinka lexemes ordered_lexemes_tuple = ( 'abany', 'abaany', 'abaŋ', 'abenh', 'abeŋ', 'aber', 'abeer', 'abëër', 'abeeric', 'aberŋic', 'abuɔ̈c', 'abuɔk', 'abuɔɔk', 'abuɔ̈k', 'abur', 'acut', 'acuut', 'acuth', ...
_____no_output_____
MIT
collation/el_collation.ipynb
enabling-languages/dinka
Pandas dataframes
ddf = pd.read_csv("../word_frequency/unilex/din.txt", sep='\t', skiprows = range(2,5)) random_ddf = ddf.sample(frac=1) sorted_ddf = elcol.sorted_(random_ddf, lang, random_ddf['Form']) sorted_ddf.head(30)
_____no_output_____
MIT
collation/el_collation.ipynb
enabling-languages/dinka
Pandas series
random_words = random_ddf['Form'] sorted_words = elcol.sorted_(random_words, lang, random_words)
_____no_output_____
MIT
collation/el_collation.ipynb
enabling-languages/dinka
What is DCT (discrete cosine transformation) ?- This notebook creates arbitrary consumption functions at both 1-dimensional and 2-dimensional grids and illustrate how DCT approximates the full-grid function with different level of accuracies. - This is used in [DCT-Copula-Illustration notebook](DCT-Copula-Illustration...
# Setup def in_ipynb(): try: if str(type(get_ipython())) == "<class 'ipykernel.zmqshell.ZMQInteractiveShell'>": return True else: return False except NameError: return False # Determine whether to make the figures inline (for spyder or jupyter) # vs whatever is t...
For accuracy level of 0.999, 10 basis functions are used For accuracy level of 0.99, 5 basis functions are used For accuracy level of 0.9, 3 basis functions are used For accuracy level of 0.8, 2 basis functions are used For accuracy level of 0.5, 1 basis functions are used
Apache-2.0
REMARKs/BayerLuetticke/notebooks/DCT.ipynb
MridulS/REMARK
CU Woot Math Method 2 for unsupervosed discovery of new behavior traits 1) Convert response field dictionary into a document 2) Develop word vector using term frequency - inverse document frequency 3) Use K-Means to cluster documents 4) Map traits to clusters to validate techniqueIn the first results presented to Woot...
## Connect to local DB client = MongoClient('localhost', 27017) print ("Setup db access") # # Get collections from mongodb # #db = client.my_test_db db = client.test chunk = 100000 start = 0 end = start + chunk #reponses = db.anon_student_task_responses.find({'correct':False})[start:end] reponses = db.anon_student_ta...
_____no_output_____
MIT
working/EDA_WM-BrianMc-topics-Method2-heat_map-100-clusters-random62.ipynb
bdmckean/woot_math_analysis
Sample Documents
for idx in range(20): print ("Sample number:", idx, "\n", df3.iloc[idx]['response_doc']) data_samples = df3['response_doc'] n_features = 1000 n_samples = len(data_samples) n_topics = 50 n_top_words = 20 print("Extracting tf-idf features ...") tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, ...
_____no_output_____
MIT
working/EDA_WM-BrianMc-topics-Method2-heat_map-100-clusters-random62.ipynb
bdmckean/woot_math_analysis
Analysis of stock prices using PCA / Notebook 3In this notebook we will study the dimensionality of stock price sequences, and show that they lie between the 1D of smooth functions and 2D of rapidly varying functions.The mathematicians Manuel Mandelbrot and Richard Hudson wrote a book titled [The Misbehavior of Market...
import findspark findspark.init() from pyspark import SparkContext #sc.stop() sc = SparkContext(master="local[3]") from pyspark.sql import * sqlContext = SQLContext(sc) %pylab inline import numpy as np df=sqlContext.read.csv('../Data/SP500.csv',header='true',inferSchema='true') df.count() columns=df.columns col=[c ...
_____no_output_____
MIT
Code/3.Dimensionality.ipynb
vnnsrk/Understanding-stock-data---Field-clustering-and-dimensionality
We generate graphs like the ones below for your analysis of dimensionality on the stocks ![Graph for Analysing Stocks](figs/plots.png)
pickleFile="Tester/Dimensionality.pkl"
_____no_output_____
MIT
Code/3.Dimensionality.ipynb
vnnsrk/Understanding-stock-data---Field-clustering-and-dimensionality
Finding DimensionWe find the dimension for a particular ticker using its sequence of data Sample Input:```python dimension = Box_count([sequence of AAPL], 'AAPL')``` Sample Output:dimension = 1.28
from scipy.optimize import curve_fit import pandas as pd def f( x, A, Df ): ''' User defined function for scipy.optimize.curve_fit(), which will find optimal values for A and Df. ''' return Df * x + A def count_boxes(PriceSequence, n): length = len(PriceSequence) PriceSequence = map(...
_____no_output_____
MIT
Code/3.Dimensionality.ipynb
vnnsrk/Understanding-stock-data---Field-clustering-and-dimensionality
PySDDR: An Advanced TutorialIn the beginner's guide only tabular data was used as input to the PySDDR framework. In this advanced tutorial we show the effects when combining structured and unstructured data. Currently, the framework only supports images as unstructured data.We will use the MNIST dataset as a source fo...
# import the sddr module from sddr import Sddr import torch import torch.nn as nn import torch.optim as optim import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #set seeds for reproducibility torch.manual_seed(1) np.random.seed(1)
_____no_output_____
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
User inputs First the user defines the data to be used. The data is loaded and if it does not already exist, a column needs to be added to the tabular data describing the unstructured data - structured data correspondence. In the example below we add a column where each item includes the name of the image to which the...
data_path = '../data/mnist_data/tab.csv' data = pd.read_csv(data_path,delimiter=',') # append a column for the numbers: each data point contains a file name of the corresponding image for i in data.index: data.loc[i,'numbers'] = f'img_{i}.jpg'
_____no_output_____
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
Next the distribution, formulas and training parameters are defined. The size of each image is ```28x28``` so our neural network has a layer which flattens the input, which is followed by a linear layer of input size ```28x28``` and an output size of ```128```. Finally, this is followed by a ```ReLU``` for the activati...
# define distribution and the formula for the distibutional parameter distribution = 'Normal' formulas = {'loc': '~ -1 + spline(x1, bs="bs", df=10) + x2 + dnn(numbers) + spline(x3, bs="bs", df=10)', 'scale': '~1' } # define the deep neural networks' architectures and output shapes used in th...
_____no_output_____
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
InitializationThe sddr instance is initialized with the parameters given by the user in the previous step:
sddr = Sddr(output_dir=output_dir, distribution=distribution, formulas=formulas, deep_models_dict=deep_models_dict, train_parameters=train_parameters, )
Using device: cpu
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
TrainingThe sddr network is trained with the data defined above and the loss curve is plotted.
sddr.train(structured_data=data, target="y_gen", unstructured_data = unstructured_data, plot=True)
Beginning training ... Train Epoch: 0 Training Loss: 129.044235 Train Epoch: 0 Validation Loss: 143.731430 Train Epoch: 100 Training Loss: 98.628090 Train Epoch: 100 Validation Loss: 118.442505 Train Epoch: 200 Training Loss: 72.697281 Train Epoch: 200 Validation Loss: 106.068893 Train Epoch: 300 Training...
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
Evaluation - Visualizing the partial effectsIn this case the data is assumed to follow a normal distribution, in which case two distributional parameters, loc and scale, need to be estimated. Below we plot the partial effects of each smooth term.Remember the partial effects are computed by: partial effect = smooth_fea...
partial_effects_loc = sddr.eval('loc',plot=True) partial_effects_scale = sddr.eval('scale',plot=True)
Nothing to plot. No (non-)linear partial effects specified for this parameter. (Deep partial effects are not plotted.)
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
As we can see the distributional parameter loc has two parial effects, one sinusoidal and one quadratic. The parameter scale expectedly has no partial effect since the formula only includes an intercept.Next we retrieve our ground truth data and compare it with the model's estimation
# compare prediction of neural network with ground truth data_pred = data.loc[:,:] ground_truth = data.loc[:,'y_gen'] # predict returns partial effects and a distributional layer that gives statistical information about the prediction distribution_layer, partial_effect = sddr.predict(data_pred, ...
Predicted variance for first sample: tensor([1.3674])
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
The comparison shows that for most samples the predicted and true values are directly propotional.Next we want to check if the model learned the correct correspondence of images and numbers
# we create a copy of our original structured data where we set all inputs but the images to be zero data_pred_copy = data.copy() data_pred_copy.loc[:,'x1'] = 0 data_pred_copy.loc[:,'x2'] = 0 data_pred_copy.loc[:,'x3'] = 0 # and make a prediction using only the images distribution_layer, partial_effect = sddr.predict(...
_____no_output_____
MIT
tutorials/AdvancedTutorial.ipynb
felixGer/PySDDR
Simple Linear RegressionEstimated time needed: **15** minutes ObjectivesAfter completing this lab you will be able to:* Use scikit-learn to implement simple Linear Regression* Create a model, train it, test it and use the model Importing Needed packages
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np %matplotlib inline
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Downloading DataTo download the data, we will use !wget to download it from IBM Object Storage.
!wget -O FuelConsumption.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
**Did you know?** When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) Understanding the D...
df = pd.read_csv("FuelConsumption.csv") # take a look at the dataset df.head()
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Data ExplorationLet's first have a descriptive exploration on our data.
# summarize the data df.describe()
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Let's select some features to explore more.
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] cdf.head(9)
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
We can plot each of these features:
viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']] viz.hist() plt.show()
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Now, let's plot each of these features against the Emission, to see how linear their relationship is:
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue') plt.xlabel("FUELCONSUMPTION_COMB") plt.ylabel("Emission") plt.show() plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue') plt.xlabel("Engine size") plt.ylabel("Emission") plt.show()
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
PracticePlot **CYLINDER** vs the Emission, to see how linear is their relationship is:
# write your code here
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Click here for the solution```pythonplt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')plt.xlabel("Cylinders")plt.ylabel("Emission")plt.show()``` Creating train and test datasetTrain/Test Split involves splitting the dataset into training and testing sets that are mutually exclusive. After which, you train with...
msk = np.random.rand(len(df)) < 0.8 train = cdf[msk] test = cdf[~msk]
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Simple Regression ModelLinear Regression fits a linear model with coefficients B = (B1, ..., Bn) to minimize the 'residual sum of squares' between the actual value y in the dataset, and the predicted value yhat using linear approximation. Train data distribution
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') plt.xlabel("Engine size") plt.ylabel("Emission") plt.show()
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
ModelingUsing sklearn package to model data.
from sklearn import linear_model regr = linear_model.LinearRegression() train_x = np.asanyarray(train[['ENGINESIZE']]) train_y = np.asanyarray(train[['CO2EMISSIONS']]) regr.fit(train_x, train_y) # The coefficients print ('Coefficients: ', regr.coef_) print ('Intercept: ',regr.intercept_)
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
As mentioned before, **Coefficient** and **Intercept** in the simple linear regression, are the parameters of the fit line.Given that it is a simple linear regression, with only 2 parameters, and knowing that the parameters are the intercept and slope of the line, sklearn can estimate them directly from our data.Notice...
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r') plt.xlabel("Engine size") plt.ylabel("Emission")
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
EvaluationWe compare the actual values and predicted values to calculate the accuracy of a regression model. Evaluation metrics provide a key role in the development of a model, as it provides insight to areas that require improvement.There are different model evaluation metrics, lets use MSE here to calculate the acc...
from sklearn.metrics import r2_score test_x = np.asanyarray(test[['ENGINESIZE']]) test_y = np.asanyarray(test[['CO2EMISSIONS']]) test_y_ = regr.predict(test_x) print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y))) print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2)) pr...
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Exercise Lets see what the evaluation metrics are if we trained a regression model using the `FUELCONSUMPTION_COMB` feature.Start by selecting `FUELCONSUMPTION_COMB` as the train_x data from the `train` dataframe, then select `FUELCONSUMPTION_COMB` as the test_x data from the `test` dataframe
train_x = #ADD CODE test_x = #ADD CODE
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Click here for the solution```pythontrain_x = train[["FUELCONSUMPTION_COMB"]]test_x = train[["FUELCONSUMPTION_COMB"]]``` Now train a Logistic Regression Model using the `train_x` you created and the `train_y` created previously
regr = linear_model.LinearRegression() #ADD CODE
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Click here for the solution```pythonregr = linear_model.LinearRegression()regr.fit(train_x, train_y)``` Find the predictions using the model's `predict` function and the `test_x` data
predictions = #ADD CODE
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
Click here for the solution```pythonpredictions = regr.predict(test_x)``` Finally use the `predictions` and the `test_y` data and find the Mean Absolute Error value using the `np.absolute` and `np.mean` function like done previously
#ADD CODE
_____no_output_____
MIT
9.Machine Learning with Python/ML0101EN-Reg-Simple-Linear-Regression-Co2.ipynb
iamshivprakash/IBMDataScience
March 18 Notes Fitting data to models 1. Build a model2. Create a "fitness function", i.e. something that returns a scalar "distance" between the model and the data3. Apply an "optimizer" to get the best-fit parameters
from astropy import units as u def gaussian_model(xarr, amplitude, offset, width): amplitude = u.Quantity(amplitude, u.K) offset = u.Quantity(offset, u.km/u.s) width = u.Quantity(width, u.km/u.s) xarr = u.Quantity(xarr, u.km/u.s) return amplitude * np.exp(-(xarr-offset)**2/(2.*width**2)) x = 5 ...
_____no_output_____
BSD-3-Clause
notebooks/MarchApril2016_TutorialSession/Notebook - March 18 - Part 1.ipynb
ESO-python/ESOPythonTutorials