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
- `JSON` turns any JSON-able `dict` into an expandable, filterable widget
tweet._json JSON(tweet._json)
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- `Image` generates an image from raw PNG data, a file path, or a URL
Image(tweet.user.profile_image_url)
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- `Markdown` can be used to generate rich text programmatically in a cell's output
Markdown(f""" *{tweet.user.name}* (`@{tweet.user.screen_name}`) is tweeting about **North Bay Python**! """)
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- `HTML` is able to render arbitrary HTML code
HTML('<a class="twitter-timeline" href="https://twitter.com/northbaypython?ref_src=twsrc%5Etfw">Tweets by northbaypython</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>');
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- `FileLink` generates a "smart" link to a file, relative to the notebook's working directory
FileLink('hey-nbpy.md')
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
--- We can use these building block to create rich representations and associate them with any object- Strategy 1: Register custom formatters for object types
def tweet_as_markdown(tweet): quoted_text = '\n'.join(f'> {line}' for line in tweet.text.split('\n')) author = f'--*{tweet.user.name}* (`@{tweet.user.screen_name}`) on {tweet.created_at}' return quoted_text + '\n\n' + author formatters = get_ipython().display_formatter.formatters formatters['text/markdown']...
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- Strategy 2: Implement `_repr_*_()` methods for custom classes Notes:- Let's say we want to move the tweet-counting code to its own class
class ScoreBoard: def __init__(self, items, display_top=5): self._items = items self.display_top = display_top @property def counts_by_name(self): return Counter(self._items) @property def to_display(self): return self.counts_by_name.most_common(sel...
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
- Rich output is rendered automatically when the object is the return value of a cell - Tip: use a `;` at the end of the last line in the cell to render nothing instead- Use the `display()` function to show rich output from anywhere in a cell (e.g. in a loop) - `display()` is versatile; falls back to text repr in...
for tweet in nbpy_tweets[:10]: display(tweet) nbpy_tweets = api.search('#nbpy', count=100000) import pickle with open('nbpy_tweets.pkl', 'wb') as f: pickle.dump(nbpy_tweets, f) with open('nbpy_tweets.pkl', 'rb') as f: unpickled = pickle.load(f) len(unpickled)
_____no_output_____
MIT
1-output.ipynb
fndari/nbpy-top-tweeters
Tutorial Title A brief introduction to the tutorial that describes:- The problem that that the tutorial addresses- Who the intended audience is- The expected experience level of that audience with a concept or tool - Which environment/language it runs in If there is another similar tutorial that's more appropriate for...
## Prepare the Data
_____no_output_____
Apache-2.0
example/MXNetTutorialTemplate.ipynb
simonmaurer/BMXNet-v2
Navigation functionalityThe Navigation functionality (`veneer.navigation`) lets you query and modify the current Source model using normal Python object notation. For example:```scenario.Network.Nodes[0].Name = 'Renamed node'```This notebook introduces the navigation functionality, including how it ties into the exist...
import veneer v = veneer.Veneer(19876) v.status()
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Initialise a Queryable object`Queryable` is the main component in `veneer.navigate`. By default, a Queryable points to the scenario.
from veneer.navigate import Queryable scenario = Queryable(v) scenario.Name
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Tab completion`Queryable` objects work with the tab completion in IPython/Jupyter, including, in many cases, for nested objects:![Tab Completion on Queryable objects in Jupyter](TabCompletion.PNG)
scenario.Network.nodes.Count
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
... However this won't work after indexing into a list or dictionary:![Tab completion fails after indexing](TabCompletionFail.PNG)You can still access the properties of the list item, if you know what they're called:
scenario.Network.nodes[0].Name
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
... But if you want tab completion, create a variable **and run the cell that creates it**. Then tab into the new variable:![Tab completion into new variable](TabCompletionVariable.PNG)
node = scenario.Network.nodes[0] # node.<tab> WON'T WORK YET. You need to run this cell first # Now tab completion should work should work node.Name
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Accessing a particular node/link/fu/etcThe above examples start from the scenario - which works, but is tedious when you need a particular node or link (or all water users, etc).Here, the existing functionality under `v.model` is has been expanded to return Queryable objects that can be used for object navigation.All ...
v.model.node?
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
... So we can get a particular node, for navigation as follows.
callide = v.model.node.nav_first(nodes='Callide Dam')
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
**Note:** The function is called `nav_first` to emphasise that you will receive the **first** match for the query. So, if you query `node_types='WaterUser'`, you'll get the first Water User matched.It's likely that we'll add a more generic `nav` method at some point that allows you to get a Queryable capable of bulk op...
callide.Name callide.fullSupplyLevel callide.fullSupplyVolume callide.fullSupplyVolume = 136300000 callide.fullSupplyVolume
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
**Note:** Changing one thing may have a side effect, impacting another property:
callide.fullSupplyLevel
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
If a property can't be set this way, it *should* tell you:
# CAUSES EXCEPTION #callide.fullSupplyLevel = 216
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Things aren't necessarily as they seem!The above examples suggest that the following would work:
# Would be nice, but doesn't work... #callide.fullSupplyVolume = 1.1 * callide.fullSupplyVolume
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
The reason is, `callide.fullSupplyVolume` is, itself, a `Queryable` object:
callide.fullSupplyVolume.__class__
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
So, although it prints out as a number, it is in fact a reference to the value within the model.If you want to actually use the *value* in an expression (eg to set another property), you'll need to use the `
callide.fullSupplyVolume = 1.1 * callide.fullSupplyVolume._eval_() callide.fullSupplyVolume callide.fullSupplyVolume = callide.fullSupplyVolume._eval_() / 1.1 callide.fullSupplyVolume
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Evaluating a QueryableIt's not ideal to need to call `._eval_()` and we plan to improve this over time.Also, the `_eval_()` workaround only works for simple types - numbers, strings, booleans, etc. It doesn't work for complex objects, such as Nodes, Links and model instances.For example you CANNOT do this at the momen...
callide.Node.location.E
_____no_output_____
ISC
doc/examples/navigation/0-Introduction.ipynb
flowmatters/veneer-py
Generate a SWOT swath.This example lets us understand how to initialize the simulation parameters (error, SSH interpolation, orbit), generate an orbit, generate a swath, interpolate the SSH, and simulate the measurement errors. Finally, we visualize the simulated data. Simulation setupThe configuration is defined usin...
import swot_simulator configuration = dict( # The swath contains in its centre a central pixel divided in two by the # reference ground track. central_pixel=True, # Distance, in km, between two points along track direction. delta_al=2.0, # Distance, in km, between two points across track directi...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
We create the parameter object for our simulation.
import swot_simulator.settings parameters = swot_simulator.settings.Parameters(configuration)
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
---**Note**The [Parameter](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.settings.Parameters.htmlswot_simulator.settings.Parameters) class exposes the [load_default](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.settings.Parameters.load_default.htmlswot_simulator.se...
import intake cat = intake.open_catalog("https://raw.githubusercontent.com/pangeo-data/" "pangeo-datastore/master/intake-catalogs/master.yaml") ds = cat.ocean.sea_surface_height.to_dask() ds
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
To interpolate SSH, we need to implement a class that must define a method tointerpolate the data under the swath. This class must be derived from the[CartesianGridHandler](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.plugins.data_handler.CartesianGridHandler.html)class to be correctly taken...
import pyinterp.backends.xarray import numpy import xarray # import swot_simulator.plugins.data_handler class CMEMS(swot_simulator.plugins.data_handler.CartesianGridHandler): """ Interpolation of the SSH AVISO (CMEMS L4 products). """ def __init__(self, adt): self.adt = adt ts = adt.ti...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Now we can update our parameters.
parameters.ssh_plugin = CMEMS(ds)
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Initiating orbit propagator.Initialization is simply done by [loading](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.orbit_propagator.load_ephemeris.htmlswot_simulator.orbit_propagator.load_ephemeris) the ephemeris file. The satellite's one-day pass is taken into account in this case.
import swot_simulator.orbit_propagator with open(parameters.ephemeris, "r") as stream: orbit = swot_simulator.orbit_propagator.calculate_orbit(parameters, stream)
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Iterate on the half-orbits of a period.To iterate over all the half-orbits of a period, call the method [iterate](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.orbit_propagator.Orbit.iterate.htmlswot_simulator.orbit_propagator.Orbit.iterate). This method returns all cycle numbers, trace num...
first_date = numpy.datetime64("2000-01-01") iterator = orbit.iterate(first_date) cycle_number, pass_number, date = next(iterator) cycle_number, pass_number, date
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Initialization of measurement error generatorsError initialization is done simply by calling the appropriate [class](https://swot-simulator.readthedocs.io/en/latest/generated/swot_simulator.error.generator.Generator.htmlswot_simulator.error.generator.Generator). The initialization of the wet troposphere error generato...
import swot_simulator.error.generator error_generator = swot_simulator.error.generator.Generator( parameters, first_date, orbit.orbit_duration())
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Generate the positions under the swath.To perform this task, the following function is implemented.> If the position of the pass is outside the area of interest (`parameters.area`),> the generation of the pass can return `None`.
def generate_one_track(pass_number, date, orbit): # Compute the spatial/temporal position of the satellite track = swot_simulator.orbit_propagator.calculate_pass( pass_number, orbit, parameters) # If the pass is not located in the area of interest (parameter.area) # the result of the generation...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Interpolate SSHInterpolation of the SSH for the space-time coordinates generated by the simulator.
def interpolate_ssh(parameters, track): swath_time = numpy.repeat(track.time, track.lon.shape[1]).reshape(track.lon.shape) ssh = parameters.ssh_plugin.interpolate(track.lon.flatten(), track.lat.flatten(), swath_time.flatten(...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Calculation of instrumental errorsSimulation of instrumental errors. > Karin's instrumental noise can be modulated by wave heights.> The parameter SWH takes either a constant or a matrix defining> the SWH for the swath positions.
def generate_instrumental_errors(error_generator, cycle_number, pass_number, orbit, track): return error_generator.generate(cycle_number, pass_number, orbit.curvilinear_distance, ...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Calculates the sum of the simulated errors.
def sum_error(errors, swath=True): """Calculate the sum of errors""" dims = 2 if swath else 1 return numpy.add.reduce( [item for item in errors.values() if len(item.shape) == dims])
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Create the swath dataset Generation of the simulated swath. The function returns an xarray dataset for the half-orbit generated.
import swot_simulator.netcdf def generate_dataset(cycle_number, pass_number, track, ssh, noise_errors, complete_product=False): product = swot_simulator.netcdf.Swath(track, central_pixel=True) # Mask to se...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Swath generation.Now we can combine the different components to generate the swath.
import dask import dask.distributed def generate_swath(cycle_number, pass_number, date, parameters, error_generator, orbit): client = dask.distributed.get_client() # Scatter big data orbit_ = client.scatter(orbit) error_generator_ = client.scatter(error_generator) # Compute swat...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
The simulator calculation can be distributed on a Dask cluster.
import dask.distributed # A local cluster is used here. cluster = dask.distributed.LocalCluster() client = dask.distributed.Client(cluster) client error_generator_ = client.scatter(error_generator) parameters_ = client.scatter(parameters) orbit_ = client.scatter(orbit) future = client.submit(generate_swath, cycle_numb...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
To calculate a trace set you can use the following code futures = [] for cycle_number, pass_number, date in iterator: futures.append(client.submit(generate_swath, cycle_number, pass_number, date, ...
import matplotlib.pyplot import cartopy.crs import cartopy.feature %matplotlib inline
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Selection of a reduced geographical area for visualization.
selected = ds.where((ds.latitude > -50) & (ds.latitude < -40), drop=True)
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Simulated SSH measurements (Interpolated SSH and simulated instrumental errors).
fig = matplotlib.pyplot.figure(figsize=(24, 12)) ax = fig.add_subplot(1, 1, 1, projection=cartopy.crs.PlateCarree()) contourf = ax.contourf(selected.longitude, selected.latitude, selected.ssh_karin, transform=cartopy.crs.PlateCarree(), ...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Simulated KaRIN instrumental noise.
for item in selected.variables: if item.startswith("simulated_error"): variable = selected.variables[item] fig = matplotlib.pyplot.figure(figsize=(18, 8)) ax = fig.add_subplot(1, 1, 1) image = ax.imshow(variable.T, extent=[0, len(selected.num_lines), -70, 70...
_____no_output_____
BSD-3-Clause
notebooks/swath_generation.ipynb
CNES/swot_simulator
Research computing with Python------ Workflow of research computing * Literature review* Ideas - Hypothesis formulation - Methodology* Data generation - Simulation - coding by yourself or use existing models (such as [LAMMPS](http://lammps.sandia.gov/doc/Manual.html) and [OpenFOAM](https://openfoam.org/)) - Experimen...
persons = [name for name in ["Adam", "James", "Dan", "Smith"] if name.startswith("A") or name.endswith("s")] print(persons)
['Adam', 'James']
Unlicense
L01_Research_computing_with_Python.ipynb
Olaolutosin/phythosin
Read IRSM FORM
cms_xml = xml_parser.get_files('irsmform xml', folder = 'linear TSR logs') cms_xml_out = xml_parser.get_files('out xml', folder = 'linear TSR logs') cms_csv = xml_parser.get_files('CMS 10y csv', folder = 'linear TSR logs') cms_replic_basket = csv_parser.parse_csv(cms_csv) cal_basket = list(xml_parser.get_calib_basket(...
_____no_output_____
MIT
notebooks/gold standard/.ipynb_checkpoints/2. recon_tsr_strikes_normalVol-checkpoint.ipynb
nkapchenko/TSR
Kmin & Kmax reconciliation
maxe = 0 tsr_fwds, xml_fwds = [], [] for (caplet, floorlet, swaplet), swo in zip(cms_replic_basket, cal_basket): tsr_fwds.append(caplet.fwd) xml_fwds.append(swo.get_swap_rate(dsc_curve, estim_curve)) kmax = tsr.minmax_strikes(swo.vol, swo.expiry, swo.get_swap_rate(dsc_curve, estim_curve), caplet.n).kma...
OK
MIT
notebooks/gold standard/.ipynb_checkpoints/2. recon_tsr_strikes_normalVol-checkpoint.ipynb
nkapchenko/TSR
Strike ladder recon
swo = cal_basket[-1] caplet, floorlet, swaplet = cms_replic_basket[-1] fwd = swo.get_swap_rate(dsc_curve, estim_curve) nref = caplet.n minmax_strikes = tsr.minmax_strikes(swo.vol, swo.expiry, fwd, nref) neff_capl = math.ceil((minmax_strikes.kmax - minmax_strikes.fwd)/minmax_strikes.kstep) + 1 neff_floo = math.floor(...
OK
MIT
notebooks/gold standard/.ipynb_checkpoints/2. recon_tsr_strikes_normalVol-checkpoint.ipynb
nkapchenko/TSR
Weights recon
mr = xml_parser.get_tsr_params(cms_xml_out).meanRevTSRSwapRate(caplet.fixing_date) tsr_coeff = linear.get_coeff(caplet.pmnt_date, dsc_curve, swo, mr, estim_curve) tsr_weights = tsr.build_weights(minmax_strikes, neff_capl, neff_floo, tsr_coeff) # print(caplet.calib_basket.Weights.values - tsr_weights.capletWeights) pr...
OK
MIT
notebooks/gold standard/.ipynb_checkpoints/2. recon_tsr_strikes_normalVol-checkpoint.ipynb
nkapchenko/TSR
Disc(Tf, Tp) / Annuity
print(caplet.calib_basket['Disc/A'].values - tsr.get_DiscOverAnnuity(strikes_ladders.caplet_ladder, tsr_coeff)) print(colored('ALARM', 'red') if max(abs(caplet.calib_basket['Disc/A'].values -\ tsr.get_DiscOverAnnuity(strikes_ladders.caplet_ladder, tsr_coeff))) > 3e-09 else colored('OK', 'green')) # print(floorlet....
OK e-05
MIT
notebooks/gold standard/.ipynb_checkpoints/2. recon_tsr_strikes_normalVol-checkpoint.ipynb
nkapchenko/TSR
 Cyclical figurate numbersProblem 61https://projecteuler.net/minimal=61 Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...Square P4,n=n2 1, 4, 9, 16, 25, ...Pentagonal P5,...
triangle = lambda n: int( (n*(n+1))/2 ) square = lambda n: int( n**2 ) pentagonal = lambda n: int( (n*(3*n-1))/2 ) hexagonal = lambda n: ( n*(2*n-1) ) heptagonal = lambda n: int( (n*(5*n-3))/2 ) octagonal = lambda n: int( n*(3*n-2) ) # Tests assert [triangle(x) for x in range(1, 6)] == [1,3,6,10,15] assert [square(x)...
_____no_output_____
MIT
project_euler/061_Cyclical figurate numbers_incomplete.ipynb
Sabihxh/projectEuler
Analyse des décès en France (toutes causes confondues)Ce notebook a pour but de mettre les chiffres de décès de ces dernières années en France en perspective afin d'en tirer des conclusions éclairées.
# Bibliothèque d'analyse et de traitement de données import pandas as pd from pandas.api.types import CategoricalDtype print("Pandas version :", pd.__version__) import numpy as np from datetime import datetime # Bibliothèques de gestion des graphiques import matplotlib.pyplot as plt # Bibliothèques de gestion des fichi...
Pandas version : 1.1.3 Imports des bibliothèques terminés !
MIT
stats-deces.ipynb
SteamFred/data-analysis
Données sourcesLes données sources sont issues du __[Fichier des personnes décédées](https://www.data.gouv.fr/fr/datasets/fichier-des-personnes-decedees/)__ fournies en données ouvertes sur [data.gouv.fr](https://www.data.gouv.fr/fr/).Les fichiers `deces-*.txt` doivent être téléchargés dans le dossier de travail du no...
# Lister tous les fichiers qui commencent par "deces" et sont au format texte (finissent par ".txt") sourcelist = [f for f in glob.glob("deces*.txt")] # Pour chaque fichier de cette liste... for source in sourcelist: # on va créer un pendant au même nom, mais se terminant par .csv cachefile = source[0:-4] + '.c...
(Ré)génération des caches CSV terminée !
MIT
stats-deces.ipynb
SteamFred/data-analysis
Relecture du cacheCi-après, on lit tous les fichiers cache pour les concaténer en mémoire afin de faire notre analyse.Pour réinitialiser toutes les données de la "dataframe" df, c'est cette cellule qu'il faut réexécuter.
print ('Lecture des fichiers cache...') # Créer une liste de tous les csv chunks = [] cachelist = [f for f in glob.glob("deces*.csv")] for cache in cachelist: # print ('Lecture de :', cache) chunks.append(pd.read_csv(cache, sep=';', encoding='latin_1',...
Lecture des fichiers cache...
MIT
stats-deces.ipynb
SteamFred/data-analysis
ClassificationPour se simplifier l'interprétation graphique, on va classer chaque décès dans une catégorie d'âge.J'ai découpé en tranches plus ou moins fines...
df['classe'] = pd.cut(df.age, bins=[0, 18, 25, 45, 55, 65, 75, 85, 150], labels=['mineur', '18-25 ans', '26-45 ans', '46-55 ans', '56-65 ans', '66-75 ans', '76-85 ans', 'plus de 86 ans']) df.tail()
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
Nombre de décès par date par catégorieA partir de la dataframe contenant les catégories, on crée une matrice pour compter le nombre de décès par date par catégorie.
ages_df = df.groupby(['date', 'classe']).age.count().astype(np.int16).unstack() ages_df.tail()
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
Analyses graphiques Analyse graphique par classe d'âge durant le confinement en FranceAfin de rendre la courbe plus lisible (la débruiter), on utilise une fonction de lissage ewm moyenné avec un facteur alpha assez faible.Analysons la période du confinement élargie de mars à mai.Constate-t-on que pour la population au...
# Pour supprimer le lissage, mettre alpha=1 # _= est une petite astuce de Romain WaaY pour ne pas afficher de message parasite avec le graphique _=ages_df.ewm(alpha=0.2).mean().loc['2020-03':'2020-05'].plot(figsize=(18,10), legend='reverse')
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
Analyse graphique sur les 20 dernières annéesMettons maintenant en perspective la surmortalité du printemps 2020 par rapport aux 20 dernières années, toutes classes d'âge confondues.D'une manière générale, on constate des pics de décès de plus en plus hauts tous les 2 à 4 ans.Le pic de 2020 est élevé, mais semble rest...
_=df.loc['2000-09':'2020-11-25'].classe.groupby('date').count().plot(figsize=(18,8)) # Calcul des moyennes annuelles an_debut = 2001 an_fin = 2021 moyennes = pd.Series([int(ages_df.loc[str(an)].mean().sum()) for an in range(an_debut,an_fin)], index=[datetime.strptime(str(an), "%Y") for an in range(...
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
INSEE.fr : [Nombre de décès quotidiensFrance, régions et départements](https://www.insee.fr/fr/statistiques/4487988?sommaire=4487854), Fichier individuel comportant des informations sur chaque décès - 20 novembre 2020
ds2020 = pd.read_csv('DC_20202021_det.csv', sep=';', encoding='utf-8') ds2020 = ds2020.drop(['COMDEC', 'DEPDEC', 'SEXE', 'COMDOM', 'LIEUDEC2'], axis=1) nb_lignes_brut = ds2020.shape[0] ds2020 = ds2020.dropna(axis=0) print ("Nombre de lignes incomplètes retirées :", str(nb_lignes_brut - ds2020.shape[0])) ds2020.tail() d...
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
Sources des données hospitalières : https://www.data.gouv.fr/fr/datasets/donnees-hospitalieres-relatives-a-lepidemie-de-covid-19/
dcc = pd.read_csv('donnees-hospitalieres-classe-age-covid19-2021-01-09-19h03.csv', sep=';', encoding='utf-8', index_col=['jour'], # Crée un indexe sur la colonne date parse_dates=True) dcc = dcc.drop(['reg', 'hosp', 'rea', 'rad'], axis=1) nb_lignes_brut = dcc.shape[0] dcc = dc...
_____no_output_____
MIT
stats-deces.ipynb
SteamFred/data-analysis
The following additional libraries are needed to run thisnotebook. Note that running on Colab is experimental, please report a Githubissue if you have any problem.
!pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
_____no_output_____
MIT
Notebook/7/7.3.NiN.ipynb
zihan987/d2l-PaddlePaddle
7.3. 网络中的网络(NiN):label:`sec_nin`LeNet、AlexNet 和 VGG 都有一个共同的设计模式:通过一系列的卷积层与池化层来提取空间结构特征;然后通过全连接层对特征的表征进行处理。AlexNet 和 VGG 对 LeNet 的改进主要在于如何扩大和加深这两个模块。或者,可以想象在这个过程的早期使用全连接层。然而,如果使用稠密层了,可能会完全放弃表征的空间结构。*网络中的网络* (*NiN*) 提供了一个非常简单的解决方案:在每个像素的通道上分别使用多层感知机 :cite:`Lin.Chen.Yan.2013` (**7.3.1. NiN块**)回想一下,卷积层的输入和输出由四维张量组成,张量的每个轴...
import paddle import paddle.nn as nn import numpy as np class Nin(nn.Layer): def __init__(self, num_channels, num_filters, kernel_size, strides, padding): super(Nin, self).__init__() model = [ nn.Conv2D(num_channels, num_filters, kernel_size, stride=strides, padding=padding), ...
_____no_output_____
MIT
Notebook/7/7.3.NiN.ipynb
zihan987/d2l-PaddlePaddle
[**7.3.2. NiN模型**]最初的 NiN 网络是在 AlexNet 后不久提出的,显然从中得到了一些启示。NiN使用窗口形状为 $11\times 11$、$5\times 5$ 和 $3\times 3$的卷积层,输出通道数量与 AlexNet 中的相同。每个 NiN 块后有一个最大池化层,池化窗口形状为 $3\times 3$,步幅为 2。NiN 和 AlexNet 之间的一个显著区别是 NiN 完全取消了全连接层。相反,NiN 使用一个 NiN块,其输出通道数等于标签类别的数量。最后放一个 *全局平均池化层*(global average pooling layer),生成一个多元逻辑向量(logits)。NiN ...
class Net(nn.Layer): def __init__(self, num_channels, class_dim): super(Net, self).__init__() model = [ Nin(num_channels, 96, 11, strides=4, padding=0), nn.MaxPool2D(kernel_size=3, stride=2), Nin(96, 256, 5, strides=1, padding=2), nn.MaxPool2D(kernel_s...
[5, 10]
MIT
Notebook/7/7.3.NiN.ipynb
zihan987/d2l-PaddlePaddle
我们创建一个数据样本来[**查看每个块的输出形状**]。
with paddle.fluid.dygraph.guard(): net = Net(1, 10) param_info = paddle.summary(net, (1, 1, 28, 28)) print(param_info)
--------------------------------------------------------------------------- Layer (type) Input Shape Output Shape Param # =========================================================================== Conv2D-1 [[1, 1, 28, 28]] [1, 96, 5, 5] 11,712 ReLU-1 [[...
MIT
Notebook/7/7.3.NiN.ipynb
zihan987/d2l-PaddlePaddle
[**7.3.3训练模型**]和以前一样,我们使用 Fashion-MNIST 来训练模型。训练 NiN 与训练 AlexNet、VGG时相似。
import paddle import paddle.vision.transforms as T from paddle.vision.datasets import FashionMNIST # 数据集处理 transform = T.Compose([ T.Resize(64), T.Transpose(), T.Normalize([127.5], [127.5]), ]) train_dataset = FashionMNIST(mode='train', transform=transform) val_dataset = FashionMNIST(mode='test', transform...
The loss value printed in the log is the current step, and the metric is the average value of previous steps. Epoch 1/2 step 100/938 - loss: 1.7510 - acc_top1: 0.3219 - acc_top5: 0.6873 - 13ms/step step 200/938 - loss: 1.2018 - acc_top1: 0.3822 - acc_top5: 0.7639 - 13ms/step step 300/938 - loss: 0.8502 - acc_top1: 0.48...
MIT
Notebook/7/7.3.NiN.ipynb
zihan987/d2l-PaddlePaddle
Plagiarism Detection, Feature EngineeringIn this project, you will be tasked with building a plagiarism detector that examines an answer text file and performs binary classification; labeling that file as either plagiarized or not, depending on how similar that text file is to a provided, source text. Your first task ...
# NOTE: # you only need to run this cell if you have not yet downloaded the data # otherwise you may skip this cell or comment it out !wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c4147f9_data/data.zip !unzip data # import libraries import pandas as pd import numpy as np import os
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
This plagiarism dataset is made of multiple text files; each of these files has characteristics that are is summarized in a `.csv` file named `file_information.csv`, which we can read in using `pandas`.
csv_file = 'data/file_information.csv' plagiarism_df = pd.read_csv(csv_file) # print out the first few rows of data info plagiarism_df.head()
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Types of PlagiarismEach text file is associated with one **Task** (task A-E) and one **Category** of plagiarism, which you can see in the above DataFrame. Tasks, A-EEach text file contains an answer to one short question; these questions are labeled as tasks A-E. For example, Task A asks the question: "What is inheri...
# Read in a csv file and return a transformed dataframe def numerical_dataframe(csv_file='data/file_information.csv'): '''Reads in a csv file which is assumed to have `File`, `Category` and `Task` columns. This function does two things: 1) converts `Category` column values to numerical values ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Test cellsBelow are a couple of test cells. The first is an informal test where you can check that your code is working as expected by calling your function and printing out the returned result.The **second** cell below is a more rigorous test cell. The goal of a cell like this is to ensure that your code is working a...
# informal testing, print out the results of a called function # create new `transformed_df` transformed_df = numerical_dataframe(csv_file ='data/file_information.csv') # check work # check that all categories of plagiarism have a class label = 1 transformed_df.head(10) # test cell that creates `transformed_df`, if te...
Tests Passed! Example data:
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Text Processing & Splitting DataRecall that the goal of this project is to build a plagiarism classifier. At it's heart, this task is a comparison text; one that looks at a given answer and a source text, compares them and predicts whether an answer has plagiarized from the source. To effectively do this comparison, a...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import helpers # create a text column text_df = helpers.create_text_column(transformed_df) text_df.head() # after running the cell above # check out the processed text for a single file, by row index row_idx = 0 # feel free to change this index samp...
Sample processed text: inheritance is a basic concept of object oriented programming where the basic idea is to create new classes that add extra detail to existing classes this is done by allowing the new classes to reuse the methods and variables of the existing classes and new methods and classes are added to spec...
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Split data into training and test setsThe next cell will add a `Datatype` column to a given DataFrame to indicate if the record is: * `train` - Training data, for model training.* `test` - Testing data, for model evaluation.* `orig` - The task's original answer from wikipedia. Stratified samplingThe given code uses a ...
random_seed = 1 # can change; set for reproducibility """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import helpers # create new df with Datatype (train, test, orig) column # pass in `text_df` from above to create a complete dataframe, with all the information you need complete_df = helpers.train_...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Determining PlagiarismNow that you've prepared this data and created a `complete_df` of information, including the text and class associated with each file, you can move on to the task of extracting similarity features that will be useful for plagiarism classification. > Note: The following code exercises, assume that...
# Calculate the ngram containment for one answer file/source file pair in a df from sklearn.feature_extraction.text import CountVectorizer def calculate_containment(df, n, answer_filename): '''Calculates the containment between a given answer text and its associated source text. This function creates a count...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Test cellsAfter you've implemented the containment function, you can test out its behavior. The cell below iterates through the first few files, and calculates the original category _and_ containment values for a specified n and file.>If you've implemented this correctly, you should see that the non-plagiarized have l...
# select a value for n n = 3 # indices for first few files test_indices = range(5) # iterate through files and calculate containment category_vals = [] containment_vals = [] for i in test_indices: # get level of plagiarism for a given file index category_vals.append(complete_df.loc[i, 'Category']) # calcu...
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
QUESTION 1: Why can we calculate containment features across *all* data (training & test), prior to splitting the DataFrame for modeling? That is, what about the containment calculation means that the test and training data do not influence each other? **Answer:**Testing and training data need to be split while traini...
# Compute the normalized LCS given an answer text and a source text def lcs_norm_word(answer_text, source_text): '''Computes the longest common subsequence of words in two texts; returns a normalized value. :param answer_text: The pre-processed text for an answer text :param source_text: The pre-proce...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Test cellsLet's start by testing out your code on the example given in the initial description.In the below cell, we have specified strings A (answer text) and S (original source text). We know that these texts have 20 words in common and the submitted answer is 27 words long, so the normalized, longest common subsequ...
# Run the test scenario from above # does your function return the expected value? A = "i think pagerank is a link analysis algorithm used by google that uses a system of weights attached to each element of a hyperlinked set of documents" S = "pagerank is a link analysis algorithm used by the google internet search en...
LCS = 0.7407407407407407 Test passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
This next cell runs a more rigorous test.
# run test cell """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # test lcs implementation # params: complete_df from before, and lcs_norm_word function tests.test_lcs(complete_df, lcs_norm_word)
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Finally, take a look at a few resultant values for `lcs_norm_word`. Just like before, you should see that higher values correspond to higher levels of plagiarism.
# test on your own test_indices = range(5) # look at first few files category_vals = [] lcs_norm_vals = [] # iterate through first few docs and calculate LCS for i in test_indices: category_vals.append(complete_df.loc[i, 'Category']) # get texts to compare answer_text = complete_df.loc[i, 'Text'] task...
Original category values: [0, 3, 2, 1, 0] Normalized LCS values: [0.1917808219178082, 0.8207547169811321, 0.8464912280701754, 0.3160621761658031, 0.24257425742574257]
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
--- Create All FeaturesNow that you've completed the feature calculation functions, it's time to actually create multiple features and decide on which ones to use in your final model! In the below cells, you're provided two helper functions to help you create multiple features and store those in a DataFrame, `features_...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Function returns a list of containment features, calculated for a given n # Should return a list of length 100 for all files in a complete_df def create_containment_features(df, n, column_name=None): containment_values = [] if(colum...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Creating LCS featuresBelow, your complete `lcs_norm_word` function is used to create a list of LCS features for all the answer files in a given DataFrame (again, this assumes you are passing in the `complete_df`. It assigns a special value for our original, source files, -1.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Function creates lcs feature and add it to the dataframe def create_lcs_features(df, column_name='lcs_word'): lcs_values = [] # iterate through files in dataframe for i in df.index: # Computes LCS_norm words feature using...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
EXERCISE: Create a features DataFrame by selecting an `ngram_range`The paper suggests calculating the following features: containment *1-gram to 5-gram* and *longest common subsequence*. > In this exercise, you can choose to create even more features, for example from *1-gram to 7-gram* containment features and *longe...
# Define an ngram range ngram_range = range(1,7) # The following code may take a minute to run, depending on your ngram_range """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ features_list = [] # Create features in a features_df all_features = np.zeros((len(ngram_range)+1, len(complete_df))) # Cal...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Correlated FeaturesYou should use feature correlation across the *entire* dataset to determine which features are ***too*** **highly-correlated** with each other to include both features in a single model. For this analysis, you can use the *entire* dataset due to the small sample size we have. All of our features try...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Create correlation matrix for just Features to determine different models to test corr_matrix = features_df.corr().abs().round(2) # display shows all of a dataframe display(corr_matrix)
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
EXERCISE: Create selected train/test dataComplete the `train_test_data` function below. This function should take in the following parameters:* `complete_df`: A DataFrame that contains all of our processed text data, file info, datatypes, and class labels* `features_df`: A DataFrame of all calculated features, such as...
# Takes in dataframes and a list of selected features (column names) # and returns (train_x, train_y), (test_x, test_y) def train_test_data(complete_df, features_df, selected_features): '''Gets selected training and test features from given dataframes, and returns tuples for training and test features and ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Test cellsBelow, test out your implementation and create the final train/test data.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ test_selection = list(features_df)[:2] # first couple columns as a test # test that the correct train/test data is created (train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, test_selection) # params: generated train/test d...
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
EXERCISE: Select "good" featuresIf you passed the test above, you can create your own train/test data, below. Define a list of features you'd like to include in your final mode, `selected_features`; this is a list of the features names you want to include.
# Select your list of features, this should be column names from features_df # ex. ['c_1', 'lcs_word'] selected_features = ['c_1', 'c_5', 'lcs_word'] """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ (train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, selected_features) ...
Training size: 70 Test size: 25 Training df sample: [[0.39814815 0. 0.19178082] [0.86936937 0.44954128 0.84649123] [0.59358289 0.08196721 0.31606218] [0.54450262 0. 0.24257426] [0.32950192 0. 0.16117216] [0.59030837 0. 0.30165289] [0.75977654 0.24571429 0.48430493] [0.5161290...
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Question 2: How did you decide on which features to include in your final model? **Answer:**lcs is one of the most important features so I have selected that. Also, its important to assess the number of words in common, so I have selected c_1 and c_5 because the correlation factor is 1 with c_4 and c_6 and also close...
def make_csv(x, y, filename, data_dir): '''Merges features and labels and converts them into one csv file with labels in the first column. :param x: Data features :param y: Data labels :param file_name: Name of csv file, ex. 'train.csv' :param data_dir: The directory where files will be ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Test cellsTest that your code produces the correct format for a `.csv` file, given some text features and labels.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ fake_x = [ [0.39814815, 0.0001, 0.19178082], [0.86936937, 0.44954128, 0.84649123], [0.44086022, 0., 0.22395833] ] fake_y = [0, 1, 1] make_csv(fake_x, fake_y, filename='to_delete.csv', data_dir='test_csv') # read in and test di...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
If you've passed the tests above, run the following cell to create `train.csv` and `test.csv` files in a directory that you specify! This will save the data in a local directory. Remember the name of this directory because you will reference it again when uploading this data to S3.
# can change directory, if you want data_dir = 'plagiarism_data' """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ make_csv(train_x, train_y, filename='train.csv', data_dir=data_dir) make_csv(test_x, test_y, filename='test.csv', data_dir=data_dir)
Path created: plagiarism_data/train.csv Path created: plagiarism_data/test.csv
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
pooja63/Plagiarism-detection
Μέρος Α
green_tif = gdal.Open("./GBDA2020_ML1/partA/green.tif") green_data = green_tif.ReadAsArray().flatten() nir_tif = gdal.Open("./GBDA2020_ML1/partA/nir.tif") nir_data = nir_tif.ReadAsArray().flatten() labels_tif = gdal.Open("./GBDA2020_ML1/partA/gt.tif") labels_data = labels_tif.ReadAsArray().flatten() labels_data = np....
_____no_output_____
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Αρχικοποιώ τα μοντέλα του πρώτου ερωτήματος, τα εκπαιδεύω και εμφανίζω τις απαιτούμενες μετρικές αξιολόγησης.
my_clfs = { "Gaussian Naive Bayes" : GaussianNB(), "K-Nearest Neighbors" : KNeighborsClassifier(n_neighbors=3,n_jobs=-1), "Simple Perceptron" : Perceptron(tol=1e-3, random_state=121,n_jobs=-1) } for title, clf in my_clfs.items(): print(title) clf.fit(X_train,y_train) pred = clf.predict(X_t...
Gaussian Naive Bayes Accuracy : 0.9980966666666666 Precision : 0.9997233383835057 Recall : 0.9928042494177983 F1 Score : 0.9962517805683377 True Positives : 75884 True Negatives : 223545 False Positives : 21 False Negatives : 550
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Με βάση τα αποτελέσματα που δίνουν οι αλγόριθμοι είναι εμφανές πως τα δεδομένα μας είναι καλώς ορισμένα και μπορούν να διαχωρίσουν τις δυο κλάσεις τέλεια. Τα αποτελέσματα είναι τέλεια με μόνο τον Gaussian classifier να πραγματοποιεί ελάχιστα λάθη. Το πρόβλημα που καλούνται να λύσουν οι αλγόριθμοι είναι σχετικά απλό, εν...
data_b = np.load("./GBDA2020_ML1/partB/indianpinearray.npy").transpose().reshape((200,-1)).transpose().astype(np.int16) labels_b = np.load("./GBDA2020_ML1/partB/IPgt.npy").flatten().astype(np.int16) clean_data = np.delete(data_b,np.where(labels_b==0),0) clean_labels = np.delete(labels_b,np.where(labels_b==0),0) clean_...
_____no_output_____
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Για τα μοντέλα που θα ζητούνται να εξεταστούν είναι απαραίτητη η προεπεξέργασία των δεδομένων. Συγκεκριμένα γίνεται κανονικοποίηση των δεδομένων. Δύο επιλογές εξετάστηκαν:1. Κανονικοποίηση Max-Min δίνονται νέες τιμές στα δεδομένα στο διάστημα [0,1]2. Κανονικοποίηση χρησιμοποιώντας τη μέση τιμή και τη διασπορά του κάθε ...
# scaler = MinMaxScaler() scaler = StandardScaler() scaler.fit(clean_data) scaled_data = scaler.transform(clean_data)
_____no_output_____
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Για τα μοντέλα MLP χρειάστηκε και ένα validation set. Για να είναι δυνατή η σύγκριση μεταξύ όλων των εξεταζόμενων μοντέλων, χρησιμοποιήθηκαν τα ίδια δεδομένα εκπαίδευσης και ελέγχου σε όλες τις περιπτώσεις.
# AM: 03400121 # train-val-test 60-10-30 , X_train, X_test, y_train, y_test = train_test_split(scaled_data, clean_labels, test_size=0.3, random_state=121,stratify=clean_labels) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.143, random_state=121,stratify=y_train) #1/7 of train set or...
_____no_output_____
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Αρχικοποιώ τα μοντέλα των SVM και RF, τα εκπαιδεύω και εμφανίζω τις απαιτούμενες μετρικές.
my_clfs_b = { "Support Vector Machine" : SVC(C=50), "Random Forest" : RandomForestClassifier(criterion="entropy",max_features="sqrt",random_state=121,n_jobs=12), } for title, clf in my_clfs_b.items(): print(title) clf.fit(X_train,y_train) pred = clf.predict(X_test) print("Accuracy :", clf...
Support Vector Machine Accuracy : 0.6386991869918699 Precision : [0.27777778 0.61571125 0.55597015 0.80519481 0.5112782 0.52763819 0.5 0.7 0.5 0.6294964 0.68970013 0.53157895 0.54054054 0.74185464 0.68918919 0.72727273] Recall : [0.35714286 0.67757009 0.59839357 0.87323944 0.46896552 0.47945205...
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
Για τα μονέλα MLP δημιουργήθηκαν δυο απλά δίκτυα. Το πρώτο αποτελείται από ένα shallow network χωρίς κανένα κρυφό επίπεδο, το οποίο προβάλει την είσοδο των 200 χαρακηριστικών στις 16 κατηγορίες εξόδου. Ως δευτερη αρχιτεκτονική για τα MLP δημιουργήθηκε ένα δίκτυο με 3 κρυφά επίπεδα με 100,50,25 νευρώνες αντίστοιχα. Στο ...
import torch from torch import nn from torch import optim import torch.nn.functional as F import numpy as np from torch.utils.data import TensorDataset, DataLoader class my_MLP_V1(nn.Module): def __init__(self): super().__init__() # self.fc1 = nn.Linear(200,50) # self.fc2 = n...
Test Loss: 0.038.. Test Accuracy: 0.631 Precision : [0.33333333 0.64332604 0.546875 0.78666667 0.56557377 0.50490196 0.33333333 0.57228916 0.5 0.63773585 0.69559413 0.56424581 0.33870968 0.75193798 0.52777778 0.51851852] Recall : [0.21428571 0.68691589 0.562249 0.83098592 0.47586207 0.47031963 0.125 ...
MIT
GBDA_exercise_5.ipynb
giorgosouz/HSI-supervised-classification
MCMC visualizations
%matplotlib inline import numpy as np import matplotlib.pyplot as plt from results import MCMCResults import sys sys.path.insert(0, '/Users/bmmorris/git/friedrich') from friedrich.lightcurve import hat11_params_morris transit_params = hat11_params_morris() from corner import corner transit_params = hat11_params_morri...
_____no_output_____
MIT
example_vis_arctic.ipynb
bmorris3/stsp_osg_results
Identify the burn-in period
burn_in_step = 2000 for i in range(len(m.chi2_chains)): plt.plot(np.log(m.chi2_chains[i]), '.', color='k', alpha=0.005) plt.xlabel('step') plt.ylabel('$\log\chi^2$') #plt.axvline(burn_in_step, color='k', lw=2) plt.show() flat_radius = [] flat_phi = [] flat_theta = [] for i in range(len(m.chi2_chains)): flat_rad...
_____no_output_____
MIT
example_vis_arctic.ipynb
bmorris3/stsp_osg_results
Kontrol egiturakKontrol egiturek exekuzioaren fluxua adierazteko balio dute. Defektuz, ezekuzioa sekuentziala izango da, hau da, aginduak bata bestearen atzetik exekutatuko dira adieraziak dauden ordenean:
print(1) print(2) print(3) print(4)
1 2 3 4
MIT
KonputaziorakoSarrera-MAT/Gardenkiak/Kontrol egiturak.ipynb
mpenagar/Irakaskuntza-Docencia-2019-2020
Utility functions
def layer_extraction(dcgan, file_names): return dcgan.get_feature(FLAGS, file_names) def maxpooling(disc): kernel_stride_size = 4 maxpooling = [ tf.nn.max_pool(disc[i],ksize=[1,2**(4-i),2**(4-i),1], strides=[1,2**(4-i),2**(4-i),1],padding='SAME') for i in range(4)...
_____no_output_____
MIT
.ipynb_checkpoints/20170622 Experiment-checkpoint.ipynb
JustWon/DCGAN-Experiment
Integration
for term in range(11,15): print('%d ~ %d' % (50*term,50*(term+1))) disc_list = [] batch_list = [] file_names = [] for idx in range(50*term,50*(term+1)): patch_path ="/media/dongwonshin/Ubuntu Data/Datasets/FAB-MAP/Image Data/City Centre/patches/#300/" data = sorted(glob("%s...
1020
MIT
.ipynb_checkpoints/20170622 Experiment-checkpoint.ipynb
JustWon/DCGAN-Experiment
Descriptor Save
for idx, name in enumerate(final_batch_list): output_filename = '/media/dongwonshin/Ubuntu Data/Datasets/FAB-MAP/Image Data/City Centre/descs/' + (name.split('/')[-2])+'.desc' with open(output_filename,'at') as fp: for v in final_disc_list[idx]: fp.write('%f ' % v) fp.write('\n'...
_____no_output_____
MIT
.ipynb_checkpoints/20170622 Experiment-checkpoint.ipynb
JustWon/DCGAN-Experiment
Result Analysis
# import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg SURF_result_text = '/home/dongwonshin/Desktop/LC_text_results/20170622_SURF_result_2.txt' DCGAN_result_text = '/home/dongwonshin/Desktop/LC_text_results/20170622_DCGAN_result_128dim_2.txt' how_many = 199 with open(SURF_...
LC_cs_cnt = 82, LC_cd_cnt = 150
MIT
.ipynb_checkpoints/20170622 Experiment-checkpoint.ipynb
JustWon/DCGAN-Experiment
Loop Closure GroundTruth Text Handling
LC_corr_list = [] with open('/media/dongwonshin/Ubuntu Data/Datasets/FAB-MAP/GroundTruth Text/CityCentreGroundTruth.txt') as fp: row = 1 for line in fp: row_ele = line.strip().split(',') if ('1' in row_ele): col = 1 for r in row_ele: if (r == ...
1353 [201.13763, -174.712228] 305 [196.393236, -168.938331]
MIT
.ipynb_checkpoints/20170622 Experiment-checkpoint.ipynb
JustWon/DCGAN-Experiment