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
On ajoute ou on réécrit le jour de la semaine qu'on utilise comme variable supplémentaire.
lagged["weekday"] = lagged.date.dt.weekday X = lagged.drop(["date", "value", "notrend", "trend"], axis=1) Y = lagged["value"] X.shape, Y.shape from numpy import corrcoef corrcoef(X)
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
Etrange autant de grandes valeurs, cela veut dire que la tendance est trop forte pour calculer des corrélations, il vaudrait mieux tout recommencer avec la série $\Delta Y_t = Y_t - Y_{t-1}$. Bref, passons...
X.columns
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
Une régression linéaire car les modèles linéaires sont toujours de bonnes baseline et pour connaître le modèle simulé, on ne fera pas beaucoup mieux.
from sklearn.linear_model import LinearRegression clr = LinearRegression() clr.fit(X, Y) from sklearn.metrics import r2_score r2_score(Y, clr.predict(X)) clr.coef_
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
On retrouve la saisonnalité, $Y_t$ et $Y_{t-6}$ sont de mèches.
for i in range(1, X.shape[1]): print("X(t-%d)" % (i), r2_score(Y, X.iloc[:, i]))
X(t-1) -0.5799344874123231 X(t-2) -1.0271995693021703 X(t-3) -1.2451181610331497 X(t-4) -1.0497781280554928 X(t-5) -0.6300696727754616 X(t-6) 0.8212380818165589 X(t-7) -0.643903114304551 X(t-8) -1.09689904382877
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
Auparavant (l'année dernière en fait), je construisais deux bases, apprentissage et tests, comme ceci :
n = X.shape[0] X_train = X.iloc[:n * 2//3] X_test = X.iloc[n * 2//3:] Y_train = Y[:n * 2//3] Y_test = Y[n * 2//3:]
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
Et puis *scikit-learn* est arrivée avec [TimeSeriesSplit](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html).
from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit(n_splits=5) for train_index, test_index in tscv.split(lagged): data_train, data_test = lagged.iloc[train_index, :], lagged.iloc[test_index, :] print("TRAIN:", data_train.shape, "TEST:", data_test.shape)
TRAIN: (107, 13) TEST: (104, 13) TRAIN: (211, 13) TEST: (104, 13) TRAIN: (315, 13) TEST: (104, 13) TRAIN: (419, 13) TEST: (104, 13) TRAIN: (523, 13) TEST: (104, 13)
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
Et on calé une forêt aléatoire...
import warnings from sklearn.ensemble import RandomForestRegressor clr = RandomForestRegressor() def train_test(clr, train_index, test_index): data_train = lagged.iloc[train_index, :] data_test = lagged.iloc[test_index, :] clr.fit(data_train.drop(["value", "date", "notrend", "trend"], ...
0.6795844303954097 0.8643514472109561 0.8438674497139955 0.889424015517347 0.8566080912412136 0.8108804128996021 0.652299214153693 0.9082580468326908 0.9146950904017541
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
2 ans coupé en 5, soit tous les 5 mois, ça veut dire que ce découpage inclut parfois Noël, parfois l'été et que les performances y seront très sensibles.
from sklearn.metrics import r2_score r2 = r2_score(data_test.value, clr.predict(data_test.drop(["value", "date", "notrend", "trend"], axis=1).as_matrix())) r2
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
On compare avec le $r_2$ avec le même $r_2$ obtenu en utilisant $Y_{t-1}$, $Y_{t-2}$, ... $Y_{t-d}$ comme prédiction.
for i in range(1, 9): print(i, ":", r2_score(data_test.value, data_test["lag%d" % i])) lagged[:5]
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
En fait le jour de la semaine est une variable catégorielle, on crée une colonne par jour.
from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder cols = ['lag1', 'lag2', 'lag3', 'lag4', 'lag5', 'lag6', 'lag7', 'lag8'] ct = ColumnTransformer( [('pass', "passthrough", cols), ("dummies", OneHotEncoder(), ["weekday"])]) pred = ct.fit(lagged).transfo...
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
On met tout dans un pipeline parce que c'est plus joli, plus pratique aussi.
from sklearn.pipeline import make_pipeline from sklearn.decomposition import PCA, TruncatedSVD cols = ['lag1', 'lag2', 'lag3', 'lag4', 'lag5', 'lag6', 'lag7', 'lag8'] model = make_pipeline( make_pipeline( ColumnTransformer( [('pass', "passthrough", cols), ...
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
C'est plus facile à voir visuellement.
from mlinsights.plotting import pipeline2dot dot = pipeline2dot(model, lagged) from jyquickhelper import RenderJsDot RenderJsDot(dot) r2_score(lagged['value'], model.predict(lagged))
_____no_output_____
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
TemplatingComplètement hors sujet mais utile.
from jinja2 import Template template = Template('Hello {{ name }}!') template.render(name='John Doe') template = Template(""" {{ name }} {{ "-" * len(name) }} Possède : {% for i in range(len(meubles)) %} - {{meubles[i]}}{% endfor %} """) meubles = ['table', "tabouret"] print(template.render(name='John Doe Doe', len=len...
John Doe Doe ------------ Possède : - table - tabouret
MIT
_doc/notebooks/td2a_ml/seasonal_timeseries.ipynb
Jerome-maker/ensae_teaching_cs
ETL ProcessesUse this notebook to develop the ETL process for each of your tables before completing the `etl.py` file to load the whole datasets.
import os import glob import psycopg2 import pandas as pd from sql_queries import * conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=student") cur = conn.cursor() conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=student password=student") cur = conn.cursor() #YD: set auto com...
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Process `song_data`In this first part, you'll perform ETL on the first dataset, `song_data`, to create the `songs` and `artists` dimensional tables.Let's perform ETL on a single song file and load a single record into each table to start.- Use the `get_files` function provided above to get a list of all song JSON file...
song_files = get_files('data/song_data') print(song_files[0]) len(song_files) filepath = song_files[0] df = pd.read_json(filepath, lines=True) df.head()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
1: `songs` Table Extract Data for Songs Table- Select columns for song ID, title, artist ID, year, and duration- Use `df.values` to select just the values from the dataframe- Index to select the first (only) record in the dataframe- Convert the array to a list and set it to `song_data`
# song_id, title, artist_id, year, duration #YD: Pandas tolist() is used to convert a series to list. song_data = df[['song_id','title','artist_id','year','duration']].values.tolist()[0] song_data song_data = df[['song_id','title','artist_id','year','duration']].values[0] song_data
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Insert Record into Song TableImplement the `song_table_insert` query in `sql_queries.py` and run the cell below to insert a record for this song into the `songs` table. Remember to run `create_tables.py` before running the cell below to ensure you've created/resetted the `songs` table in the sparkify database.
cur.execute(song_table_insert, song_data) conn.commit()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Run `test.ipynb` to see if you've successfully added a record to this table.
# cur.close() # conn.close()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
2: `artists` Table Extract Data for Artists Table- Select columns for artist ID, name, location, latitude, and longitude- Use `df.values` to select just the values from the dataframe- Index to select the first (only) record in the dataframe- Convert the array to a list and set it to `artist_data`
artist_data = df[['artist_id','artist_name','artist_location','artist_latitude','artist_longitude']].values.tolist()[0] artist_data type(artist_data) artist_data = df[['artist_id','artist_name','artist_location','artist_latitude','artist_longitude']].values[0] artist_data type(artist_data)
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Insert Record into Artist TableImplement the `artist_table_insert` query in `sql_queries.py` and run the cell below to insert a record for this song's artist into the `artists` table. Remember to run `create_tables.py` before running the cell below to ensure you've created/resetted the `artists` table in the sparkify ...
cur.execute(artist_table_insert, artist_data) conn.commit()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Run `test.ipynb` to see if you've successfully added a record to this table. Process `log_data`In this part, you'll perform ETL on the second dataset, `log_data`, to create the `time` and `users` dimensional tables, as well as the `songplays` fact table.Let's perform ETL on a single log file and load a single record i...
log_files = get_files('data/log_data') filepath = log_files[0] df = pd.read_json(filepath, lines=True) df.head()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
3: `time` Table Extract Data for Time Table- Filter records by `NextSong` action- Convert the `ts` timestamp column to datetime - Hint: the current timestamp is in milliseconds- Extract the timestamp, hour, day, week of year, month, year, and weekday from the `ts` column and set `time_data` to a list containing these...
df = df[df['page'] == 'NextSong'] df.head() #YD: note that to_datetime default is 'ns' t = pd.to_datetime(df['ts'], unit='ms') t.head() t = df.copy() t['ts'] = pd.to_datetime(df['ts'], unit='ms') t.head() time_data = t['ts'].tolist() len(time_data) time_data[72].year time_data[72].day_name() time_data[72].weekday() #YD...
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Insert Records into Time TableImplement the `time_table_insert` query in `sql_queries.py` and run the cell below to insert records for the timestamps in this log file into the `time` table. Remember to run `create_tables.py` before running the cell below to ensure you've created/resetted the `time` table in the sparki...
#YD: how to insert rows one by one for i, row in time_df.iterrows(): cur.execute(time_table_insert, list(row)) conn.commit() # cur.close() # conn.close()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Run `test.ipynb` to see if you've successfully added records to this table. 4: `users` Table Extract Data for Users Table- Select columns for user ID, first name, last name, gender and level and set to `user_df`
user_df = df[['userId','firstName','lastName','gender','level']] user_df.head()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Insert Records into Users TableImplement the `user_table_insert` query in `sql_queries.py` and run the cell below to insert records for the users in this log file into the `users` table. Remember to run `create_tables.py` before running the cell below to ensure you've created/resetted the `users` table in the sparkify...
for i, row in user_df.iterrows(): cur.execute(user_table_insert, row) conn.commit()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Run `test.ipynb` to see if you've successfully added records to this table. 5: `songplays` Table Extract Data and Songplays TableThis one is a little more complicated since information from the songs table, artists table, and original log file are all needed for the `songplays` table. Since the log file does not speci...
df.head(1) df['ts'] = df['ts'] songplay_table_insert song_select import pdb for index, row in df.iterrows(): cur.execute(song_select, (row.song,row.artist,row.length)) results = cur.fetchone() if results: songid, artistid = results else: songid, artistid = None, None # pdb.set_t...
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
Run `test.ipynb` to see if you've successfully added records to this table. Close Connection to Sparkify Database
conn.close()
_____no_output_____
MIT
Project_data modeling with postgres/.ipynb_checkpoints/etl-checkpoint.ipynb
yumengdong/Data-Engineer-Nanodegree-Udacity
This notebook is designed to run in a IBM Watson Studio default runtime (NOT the Watson Studio Apache Spark Runtime as the default runtime with 1 vCPU is free of charge). Therefore, we install Apache Spark in local mode for test purposes only. Please don't use it in production.In case you are facing issues, please re...
from IPython.display import Markdown, display def printmd(string): display(Markdown('# <span style="color:red">'+string+'</span>')) if ('sc' in locals() or 'sc' in globals()): printmd('<<<<<!!!!! It seems that you are running in a IBM Watson Studio Apache Spark Notebook. Please run it in an IBM Watson Studio ...
_____no_output_____
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Welcome to exercise two of week three of “Apache Spark for Scalable Machine Learning on BigData”. In this exercise we’ll work on clustering.Let’s create our DataFrame again:
# delete files from previous runs !rm -f hmp.parquet* # download the file containing the data in PARQUET format !wget https://github.com/IBM/coursera/raw/master/hmp.parquet # create a dataframe out of it df = spark.read.parquet('hmp.parquet') # register a corresponding query table df.createOrReplaceTempView('df'...
--2020-12-09 04:39:14-- https://github.com/IBM/coursera/raw/master/hmp.parquet Resolving github.com (github.com)... 140.82.114.4 Connecting to github.com (github.com)|140.82.114.4|:443... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: https://github.com/IBM/skillsnetwork/raw/master/...
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Let’s reuse our feature engineering pipeline.
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler, Normalizer from pyspark.ml.linalg import Vectors from pyspark.ml import Pipeline indexer = StringIndexer(inputCol="class", outputCol="classIndex") encoder = OneHotEncoder(inputCol="classIndex", outputCol="categoryVec") vectorAssembler = Vect...
+---+---+---+--------------------+-----------+----------+--------------+----------------+--------------------+ | x| y| z| source| class|classIndex| categoryVec| features| features_norm| +---+---+---+--------------------+-----------+----------+--------------+----------------+---------...
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Now let’s create a new pipeline for kmeans.
from pyspark.ml.clustering import KMeans from pyspark.ml.evaluation import ClusteringEvaluator kmeans = KMeans(featuresCol="features").setK(14).setSeed(1) pipeline = Pipeline(stages=[vectorAssembler, kmeans]) model = pipeline.fit(df) predictions = model.transform(df) evaluator = ClusteringEvaluator() silhouette = ev...
Silhouette with squared euclidean distance = 0.4020618068072166
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
We have 14 different movement patterns in the dataset, so setting K of KMeans to 14 is a good idea. But please experiment with different values for K, do you find a sweet spot? The closer Silhouette gets to 1, the better.[https://en.wikipedia.org/wiki/Silhouette\_(clustering)](https://en.wikipedia.org/wiki/Silhouette_(...
# please change the pipeline the check performance for different K, feel free to use a loop
_____no_output_____
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Now please extend the pipeline to work on the normalized features. You need to tell KMeans to use the normalized feature column and change the pipeline in order to contain the normalizer stage as well.
kmeans = KMeans($$).setK(14).setSeed(1) pipeline = $$ model = pipeline.fit(df) predictions = model.transform(df) evaluator = ClusteringEvaluator() silhouette = evaluator.evaluate(predictions) print("Silhouette with squared euclidean distance = " + str(silhouette))
_____no_output_____
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Sometimes, inflating the dataset helps, here we multiply x by 10, let’s see if the performance inceases.
from pyspark.sql.functions import col df_denormalized = df.select([col('*'),(col('x')*10)]).drop('x').withColumnRenamed('(x * 10)','x') kmeans = KMeans(featuresCol="features").setK(14).setSeed(1) pipeline = Pipeline(stages=[vectorAssembler, kmeans]) model = pipeline.fit(df_denormalized) predictions = model.transform(df...
_____no_output_____
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
Apache SparkML can be used to try many different algorithms and parametrizations using the same pipeline. Please change the code below to use GaussianMixture over KMeans. Please use the following link for your reference.[https://spark.apache.org/docs/latest/ml-clustering.htmlgaussian-mixture-model-gmm](https://spark.ap...
from pyspark.ml.clustering import GaussianMixture gmm = $$ pipeline = $$ model = pipeline.fit(df) predictions = model.transform(df) evaluator = ClusteringEvaluator() silhouette = evaluator.evaluate(predictions) print("Silhouette with squared euclidean distance = " + str(silhouette))
_____no_output_____
MIT
a6_w3_ex2.ipynb
indervirbanipal/scalable-machine-learning-on-big-data-using-apache-spark
NumPy Operations ArithmeticYou can easily perform array with array arithmetic, or scalar with array arithmetic. Let's see some examples:
import numpy as np arr = np.arange(0,10) arr + arr arr * arr arr - arr # Warning on division by zero, but not an error! # Just replaced with nan arr/arr # Also warning, but not an error instead infinity 1/arr arr**3
_____no_output_____
MIT
data-analysis/numpy/3_operations.ipynb
pbgnz/ds-ml
Universal Array FunctionsNumpy comes with many [universal array functions](http://docs.scipy.org/doc/numpy/reference/ufuncs.html), which are essentially just mathematical operations you can use to perform the operation across the array. Let's show some common ones:
#Taking Square Roots np.sqrt(arr) #Calcualting exponential (e^) np.exp(arr) np.max(arr) #same as arr.max() np.sin(arr) np.log(arr)
/Users/marci/anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:1: RuntimeWarning: divide by zero encountered in log if __name__ == '__main__':
MIT
data-analysis/numpy/3_operations.ipynb
pbgnz/ds-ml
Task 2: Image Enhancement II: Spatial SmoothingIn this task, we will implement average, gaussian, and median spatial filter.
%%bash pip install git+https://github.com/ee604/ee604_plugins # Importing required libraries import cv2 import numpy as np import matplotlib.pyplot as plt from ee604_plugins import download_dataset, cv2_imshow download_dataset(assignment_no=2, task_no=2) # download data for this assignment def avgFilter(img, kernel_s...
_____no_output_____
MIT
assignment_2/Task_2.ipynb
utkarsh530/ee604_assignments
Test---Your observation should compare the different methods for different images. Must include a sentence on which method + kernel size worked best in each case.
# Do not change codes inside this cell # Add your observations in next to next cell # Your observation should compare the different methods for different images lena_orig = cv2.imread('data/lena_gray.jpg', 0) lena_noisy_1 = cv2.imread('data/lena_noisy_1.jpg', 0) lena_noisy_2 = cv2.imread('data/lena_noisy_2.jpg', 0) le...
_____no_output_____
MIT
assignment_2/Task_2.ipynb
utkarsh530/ee604_assignments
A simple notebook to do MIRI coordinate transforms. Some functionality depends on having the JWST pipeline and/or pysiaf module installed
import numpy as np import pdb as pdb from astropy.modeling import models from asdf import AsdfFile from jwst import datamodels from jwst.assign_wcs import miri import pysiaf
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Imager transforms using standalone code plus pysiaf Import the miricoord standalone code:
import miricoord.imager.mirim_tools as mt
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Read the MIRI apertures from the SIAF
siaf = pysiaf.Siaf('MIRI')#,basepath='/Users/dlaw/jwcode/pysiaf/pysiaf/pre_delivery_data/MIRI')
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Get the MIRIM_FULL x,y reference location from the SIAF
xref,yref=siaf['MIRIM_FULL'].XDetRef,siaf['MIRIM_FULL'].YDetRef
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Note that these are in the SIAF 1-indexed reference frame; in order to use them we'll first have to transform them to the 0-indexed frame used by all MIRI coordinates code (and the JWST pipeline):
xref,yref=xref-1,yref-1 xref,yref
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Transform them to v2,v3 for filter 'F770W'
v2ref,v3ref=mt.xytov2v3(xref,yref,'F770W') v2ref,v3ref
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
This should be showing that the v2,v3 reference point of MIRIM_FULL (for which F770W is the reference filter) is -453.559, -373.814 (note that this changed in CDP-7) We can also convert a given location to RA,DEC if we assume a few JWST attitude keywords. First import the miricoord telescope tools module:
import miricoord.tel.tel_tools as teltools
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Let's pretend that the telescope pointing had the reference point looking at RA=312.5, DEC=-76.0, and had spacecraft roll 73 degrees
raref,decref,rollref=312.5,-76.0,73.0
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Given that, we want to know where the location v2,v3=(-400,-420) is (this is somewhere in the coronagraphs):
v2,v3=[-400.],[-420.] ra,dec,newroll=teltools.jwst_v2v3toradec(v2,v3,v2ref=v2ref,v3ref=v3ref,raref=raref,decref=decref,rollref=rollref)
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
The RA,dec of this point is:
ra,dec
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
And the local roll at this new location is:
newroll
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Note that if we instead had a FITS header with the appropriate keywords, we could have passed that to jwst_v2v3toradec instead of individual values. Now let's do an imager transform using the JWST pipeline code Import the miricoord pipeline access code:
import miricoord.imager.mirim_pipetools as mpt v2ref,v3ref=mpt.xytov2v3(xref,yref,'F770W') v2ref,v3ref
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
This should be the same answer as before, but under the hood it used the JWST pipeline! We can also access the pipeline distortion model directly:
model=mpt.xytov2v3model('F770W')
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
And use that to do forward transforms:
model(xref,yref)
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
And backward transforms:
model.inverse(v2ref,v3ref)
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Now do a conversion to Ideal coordinates using the SIAF apertures: Let's work out where v2,v3=-415.069, -400.576 is for the LRS slit
v2,v3=-415.069, -400.576 xideal,yideal=mt.v2v3toIdeal(v2,v3,'MIRIM_SLIT') xideal,yideal
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
It's 0,0, which makes sense since this was the MIRIM_SLIT reference point. Now see what the lower-left corner of the LRS slit corresponds to in the SIAF:
xideal,yideal=siaf['MIRIM_SLIT'].XIdlVert1,siaf['MIRIM_SLIT'].YIdlVert1 v2,v3=mt.Idealtov2v3(xideal,yideal,'MIRIM_SLIT') xideal,yideal,v2,v3 siaf['MIRIM_SLIT'].plot()
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
As another example, APT requires Ideal coordinate offsets from the reference point If we wanted to see where an offset of XIdeal,YIdeal=10,0 in filter F2300C would land a star on the imager detector compared to the nominal Lyot coronagraph reference point in F770W:
xideal,yideal=10,0 v2,v3=mt.Idealtov2v3(xideal,yideal,'MIRIM_CORONLYOT') x,y=mt.v2v3toxy(v2,v3,'F2300C') print(x,y) siaf['MIRIM_CORONLYOT'].plot()
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Now we'll do an MRS transform using standalone code plus pysiaf
import miricoord.mrs.mrs_tools as mrst
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Get the MRS v2,v3 reference point from the SIAF
v2ref,v3ref=siaf['MIRIFU_CHANNEL1A'].V2Ref,siaf['MIRIFU_CHANNEL1A'].V3Ref v2ref,v3ref siaf['MIRIFU_CHANNEL1A'].plot()
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Figure out what alpha,beta this is in Channel 1A
alpha,beta=mrst.v2v3toab(v2ref,v3ref,'1A') alpha,beta
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
By design, it's zero,zero since this was the reference point Now find out where pixels 50,60 55,60 and 60,60 on the SHORT detector would be for Ch1A
x,y=[50,55,60],[60,60,60] temp=mrst.xytoabl(x,y,'1A',trim=1) temp
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Note that here the return is actually a dictionary of information, and that it is only 2 elements long. This is because we specified trim=1, which will remove any values that do not correspond to a light-sensitive slice.
v2,v3=mrst.abtov2v3(temp['alpha'],temp['beta'],'1A') v2,v3
_____no_output_____
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Now we'll do an MRS transform using the pipeline code
import miricoord.mrs.mrs_pipetools as mrspt x,y=30.31,511.0 a,b,l=mrspt.xytoabl(x,y,'1A') print(a,b,l)
0.4612954052724527 0.0 5.343680519509376
BSD-3-Clause
miricoord/BasicTransforms.ipynb
STScI-MIRI/miricoord
Copyright 2019 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License");
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Text Classification with Movie Reviews View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This notebook classifies movie reviews as *positive* or *negative* using the text of the review. This is an example of *binary*—or two-class—classification, an importan...
import numpy as np import tensorflow as tf import tensorflow_hub as hub import tensorflow_datasets as tfds import matplotlib.pyplot as plt print("Version: ", tf.__version__) print("Eager mode: ", tf.executing_eagerly()) print("Hub version: ", hub.__version__) print("GPU is", "available" if tf.config.list_physical_de...
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Download the IMDB datasetThe IMDB dataset is available on [TensorFlow datasets](https://github.com/tensorflow/datasets). The following code downloads the IMDB dataset to your machine (or the colab runtime):
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], batch_size=-1, as_supervised=True) train_examples, train_labels = tfds.as_numpy(train_data) test_examples, test_labels = tfds.as_numpy(test_data)
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Explore the data Let's take a moment to understand the format of the data. Each example is a sentence representing the movie review and a corresponding label. The sentence is not preprocessed in any way. The label is an integer value of either 0 or 1, where 0 is a negative review, and 1 is a positive review.
print("Training entries: {}, test entries: {}".format(len(train_examples), len(test_examples)))
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Let's print first 10 examples.
train_examples[:10]
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Let's also print the first 10 labels.
train_labels[:10]
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Build the modelThe neural network is created by stacking layers—this requires three main architectural decisions:* How to represent the text?* How many layers to use in the model?* How many *hidden units* to use for each layer?In this example, the input data consists of sentences. The labels to predict are either 0 or...
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1" hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], dtype=tf.string, trainable=True) hub_layer(train_examples[:3])
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Let's now build the full model:
model = tf.keras.Sequential() model.add(hub_layer) model.add(tf.keras.layers.Dense(16, activation='relu')) model.add(tf.keras.layers.Dense(1)) model.summary()
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
The layers are stacked sequentially to build the classifier:1. The first layer is a TensorFlow Hub layer. This layer uses a pre-trained Saved Model to map a sentence into its embedding vector. The model that we are using ([google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/...
model.compile(optimizer='adam', loss=tf.losses.BinaryCrossentropy(from_logits=True), metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Create a validation setWhen training, we want to check the accuracy of the model on data it hasn't seen before. Create a *validation set* by setting apart 10,000 examples from the original training data. (Why not use the testing set now? Our goal is to develop and tune our model using only the training data, then use ...
x_val = train_examples[:10000] partial_x_train = train_examples[10000:] y_val = train_labels[:10000] partial_y_train = train_labels[10000:]
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Train the modelTrain the model for 40 epochs in mini-batches of 512 samples. This is 40 iterations over all samples in the `x_train` and `y_train` tensors. While training, monitor the model's loss and accuracy on the 10,000 samples from the validation set:
history = model.fit(partial_x_train, partial_y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Evaluate the modelAnd let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy.
results = model.evaluate(test_data, test_labels) print(results)
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%. Create a graph of accuracy and loss over time`model.fit()` returns a `History` object that contains a dictionary with everything that happened during training:
history_dict = history.history history_dict.keys()
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
There are four entries: one for each monitored metric during training and validation. We can use these to plot the training and validation loss for comparison, as well as the training and validation accuracy:
acc = history_dict['accuracy'] val_acc = history_dict['val_accuracy'] loss = history_dict['loss'] val_loss = history_dict['val_loss'] epochs = range(1, len(acc) + 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'bo', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validat...
_____no_output_____
Apache-2.0
site/en-snapshot/hub/tutorials/tf2_text_classification.ipynb
rapsealk/docs-l10n
Sample groupingWe are going to linger into the concept of sample groups. As in the previoussection, we will give an example to highlight some surprising results. Thistime, we will use the handwritten digits dataset.
from sklearn.datasets import load_digits digits = load_digits() data, target = digits.data, digits.target
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
We will recreate the same model used in the previous exercise:a logistic regression classifier with preprocessor to scale the data.
from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline model = make_pipeline(StandardScaler(), LogisticRegression())
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
We will use the same baseline model. We will use a `KFold` cross-validationwithout shuffling the data at first.
from sklearn.model_selection import cross_val_score, KFold cv = KFold(shuffle=False) test_score_no_shuffling = cross_val_score(model, data, target, cv=cv, n_jobs=-1) print(f"The average accuracy is " f"{test_score_no_shuffling.mean():.3f} +/- " f"{test_score_no_shu...
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
Now, let's repeat the experiment by shuffling the data within thecross-validation.
cv = KFold(shuffle=True) test_score_with_shuffling = cross_val_score(model, data, target, cv=cv, n_jobs=-1) print(f"The average accuracy is " f"{test_score_with_shuffling.mean():.3f} +/- " f"{test_score_with_shuffling.std():.3f}")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
We observe that shuffling the data improves the mean accuracy.We could go a little further and plot the distribution of the testingscore. We can first concatenate the test scores.
import pandas as pd all_scores = pd.DataFrame( [test_score_no_shuffling, test_score_with_shuffling], index=["KFold without shuffling", "KFold with shuffling"], ).T
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
Let's plot the distribution now.
import matplotlib.pyplot as plt import seaborn as sns all_scores.plot.hist(bins=10, edgecolor="black", density=True, alpha=0.7) plt.xlim([0.8, 1.0]) plt.xlabel("Accuracy score") plt.legend(bbox_to_anchor=(1.05, 0.8), loc="upper left") _ = plt.title("Distribution of the test scores")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
The cross-validation testing error that uses the shuffling has lessvariance than the one that does not impose any shuffling. It means that somespecific fold leads to a low score in this case.
print(test_score_no_shuffling)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
Thus, there is an underlying structure in the data that shuffling will breakand get better results. To get a better understanding, we should read thedocumentation shipped with the dataset.
print(digits.DESCR)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
If we read carefully, 13 writers wrote the digits of our dataset, accountingfor a total amount of 1797 samples. Thus, a writer wrote several times thesame numbers. Let's suppose that the writer samples are grouped.Subsequently, not shuffling the data will keep all writer samples togethereither in the training or the te...
from itertools import count import numpy as np # defines the lower and upper bounds of sample indices # for each writer writer_boundaries = [0, 130, 256, 386, 516, 646, 776, 915, 1029, 1157, 1287, 1415, 1545, 1667, 1797] groups = np.zeros_like(target) lower_bounds = writer_boundaries[:-1] upper_bo...
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
We can check the grouping by plotting the indices linked to writer ids.
plt.plot(groups) plt.yticks(np.unique(groups)) plt.xticks(writer_boundaries, rotation=90) plt.xlabel("Target index") plt.ylabel("Writer index") _ = plt.title("Underlying writer groups existing in the target")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
Once we group the digits by writer, we can use cross-validation to take thisinformation into account: the class containing `Group` should be used.
from sklearn.model_selection import GroupKFold cv = GroupKFold() test_score = cross_val_score(model, data, target, groups=groups, cv=cv, n_jobs=-1) print(f"The average accuracy is " f"{test_score.mean():.3f} +/- " f"{test_score.std():.3f}")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
We see that this strategy is less optimistic regarding the model statisticalperformance. However, this is the most reliable if our goal is to makehandwritten digits recognition writers independent. Besides, we can as wellsee that the standard deviation was reduced.
all_scores = pd.DataFrame( [test_score_no_shuffling, test_score_with_shuffling, test_score], index=["KFold without shuffling", "KFold with shuffling", "KFold with groups"], ).T all_scores.plot.hist(bins=10, edgecolor="black", density=True, alpha=0.7) plt.xlim([0.8, 1.0]) plt.xlabel("Accuracy score") ...
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_grouping.ipynb
mehrdad-dev/scikit-learn-mooc
OSMnx + igraph for faster performanceAuthor: [Geoff Boeing](https://geoffboeing.com/)NetworkX is ubiquitous, easy to use, and sufficiently fast for most use cases. But it can be slow for analyzing very large graphs because it is pure Python, trading off speed for ease of use. Fortunately, converting OSMnx-created Netw...
import operator import igraph as ig import networkx as nx import numpy as np import osmnx as ox %matplotlib inline ox.config(use_cache=True, log_console=False) print(ox.__version__) print(ig.__version__) weight = "length"
1.1.2 0.9.9
MIT
osmnx-examples/14-osmnx-to-igraph.ipynb
w3labkr/ipynb-gis
Construct graphs
# create networkx graph G_nx = ox.graph_from_place("Piedmont, CA, USA", network_type="drive") osmids = list(G_nx.nodes) G_nx = nx.relabel.convert_node_labels_to_integers(G_nx) # give each node its original osmid as attribute since we relabeled them osmid_values = {k: v for k, v in zip(G_nx.nodes, osmids)} nx.set_node_...
_____no_output_____
MIT
osmnx-examples/14-osmnx-to-igraph.ipynb
w3labkr/ipynb-gis
Shortest paths
source = list(G_nx.nodes())[0] target = list(G_nx.nodes())[-1] %%time path1 = G_ig.get_shortest_paths(v=source, to=target, weights=weight)[0] %%time path2 = nx.shortest_path(G_nx, source, target, weight=weight) assert path1 == path2 %%time path_length1 = G_ig.shortest_paths(source=source, target=target, weights=weight)...
_____no_output_____
MIT
osmnx-examples/14-osmnx-to-igraph.ipynb
w3labkr/ipynb-gis
Centrality analysis
%%time closeness1 = G_ig.closeness(vertices=None, mode="ALL", cutoff=None, weights=weight, normalized=True) max_closeness1 = np.argmax(closeness1) %%time closeness2 = nx.closeness_centrality(G_nx, distance=weight, wf_improved=True) max_closeness2 = max(closeness2.items(), key=operator.itemgetter(1))[0] # confirm same n...
_____no_output_____
MIT
osmnx-examples/14-osmnx-to-igraph.ipynb
w3labkr/ipynb-gis
#Last amended: 12th March, 2021 # My folder: harnalashok/github/deeplearning-sequences # References: # https://www.tensorflow.org/tutorials/text/text_classification_rnn # https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/data.ipynb#scrollTo=m5bz7R1xhX1f # https://stackoverflow.com/...
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
Introduction to tensors Refer this [page](https://www.tensorflow.org/guide/tensor) Tensors are (kind of) like np.arrays. All tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one. Rank in tensor is akin to dimensions in numpy. Basics
# 2.0 Rank 0 # A "scalar" or "rank-0" tensor . # A scalar contains a single value, # and no "axes". print( tf.constant(4)) # 2.1 Rank 1 # A "vector" or "rank-1" tensor is like # a list of values. A vector has one axis: print(tf.constant([2.0, 3.0, 4.0])) # 2.2 Rank 2 # A "matr...
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
Tensor to numpy Convert a tensor to numpy array using `np.array` method or using `tensor.numpy` method:
# 3.0 Tensor to numpy np.array(s) print() s.numpy() print() np.array(rank_3_tensor) print() rank_3_tensor.numpy()
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
Basic maths on tensors Basic math on tensors, including addition, element-wise multiplication, and matrix multiplication.
# 3.1 a = tf.constant([[1, 2], [3, 4]]) b = tf.constant([[1, 2], [1, 0]]) c = tf.ones([2,3]) # 3.2 a+b print() tf.add(a,b) print() a * b print() tf.multiply(a,b) print() tf.matmul(a,b) # 3.3 This fails. Tensors are very sensitive # to data types r = tf.cons...
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
Some operations on tensors
# 4.0 c = tf.constant([[4.0, 5.0], [10.0, 1.0]]) # 4.1 Find the largest value print(tf.reduce_max(c)) # 4.2 Find the index of the largest value print(tf.argmax(c)) # 4.3 Compute the softmax # Note that each 'row' # (or axis 0) or putput # sums to 1 print(tf.nn.softmax(c))
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
Some vocabulary Tensors have shapes. Some vocabulary: > **Shape**: The length (number of elements) of each of the axes of a tensor. > **Rank**: Number of tensor axes. A scalar has rank 0, a vector has rank 1, a matrix is rank 2. > **Axis** or Dimension: A particular dimension of a tensor. > **Size**: The total ...
# 5.0 rank_4_tensor = tf.zeros([3, 2, 4, 5]) # axis 0 is 3 # axis -1 is 5
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences
![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAT4AAAGNCAYAAACIZh3rAAAgAElEQVR4nO3dWZBUVZ7H8cq8uVflvtbGTgGyCQoiAqIi7rY7arug6DTYOooLjWILDj0K7TIN0tpTLY10I9U6Q0OjoY7TXcIY2FFGE2DIaFRFdBhMmD5U+OADDzxkxH8eNLEoc7n3nHvOP2/d38M3wq7KU+dfHZxP3MyqutnU1NRECCHkstgHQAgh3bEPgBBCumMfACGEdMc+AEII6Y59AIQQ0h37AAghpDv2ARBCSHf...
# 5.2 Like in numpy arrays, we have attributes: # dtype, ndim, shape rank_4_tensor.dtype print() rank_4_tensor.ndim print() rank_4_tensor.shape print() rank_4_tensor.shape[0] print() rank_4_tensor.shape[-1] print() tf.size(rank_4_tensor).numpy()
_____no_output_____
Apache-2.0
tf data API.ipynb
harnalashok/deeplearning-sequences