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 |
|---|---|---|---|---|---|
Cleaning up a service instance*Back to [table of contents](Table-of-Contents)*To clean all data on the service instance, you can run the following snippet. The code is self-contained and does not require you to execute any of the cells above. However, you will need to have the `key.json` containing a service key in pl... | CLEANUP_EVERYTHING = False
def cleanup_everything():
import logging
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
import json
import os
if not os.path.exists("key.json"):
msg = "key.json is not found. Please follow instructions above to create a service key of... | _____no_output_____ | Apache-2.0 | exercises/ex1-DAR/teched2020-INT260_Data_Attribute_Recommendation.ipynb | SAP-samples/teched2020-INT260 |
ResumenEste cuaderno digital interactivo tiene como objetivo demostrar las relaciones entre las propiedades fisico-químicas de la vegetación y el espectro solar.Para ello haremos uso de modelos de simulación, en particular de modelos de transferencia radiativa tanto a nivel de hoja individual como a nivel de dosel veg... | %matplotlib inline
from ipywidgets import interactive, fixed
from IPython.display import display
from functions import prosail_and_spectra as fn | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Espectro de una hojaLas propiedades espectrales de una hoja (tanto su transmisividad, su reflectividad y su absortividad) dependen de su concentración de pigmentos, de su contenido de agua, su peso específico y la estructura interna de sus tejidos. Vamos a usar el modelo ProspectD, el cual es una simplificación de la ... | w_rho_leaf = interactive(fn.update_prospect_spectrum, N_leaf=fn.w_nleaf, Cab=fn.w_cab,
Car=fn.w_car, Ant=fn.w_ant, Cbrown=fn.w_cbrown, Cw=fn.w_cw, Cm=fn.w_cm)
display(w_rho_leaf) | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Observa lo siguente:* La concentración de clorofila `Cab` afecta principalmente a la región del visible (RGB) y del *red egde* (R-E), con más absorción en la región del rojo y del azul y más reflexión en el verde. Es por ello que la mayoría de las hojas presentan color verde.* El contenido de agua `Cw` afecta principal... | w_rho_soil = interactive(fn.update_soil_spectrum, soil_name=fn.w_soil)
display(w_rho_soil) | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Observa lo diferente que puede ser un espectro de suelo en comparación con el de una hoja. Esto es clave a la hora de clasificar tipos de coberturas mediante teledetección así como cuantificar el vigor/densidad vegetal del cultivo.Observa que suelos más salinos (`aridisol.salorthid`) o gipsicos (`aridisol.gypsiorthd`),... | w_rho_canopy = interactive(fn.update_4sail_spectrum,
lai=fn.w_lai, hotspot=fn.w_hotspot, leaf_angle=fn.w_leaf_angle,
sza=fn.w_sza, vza=fn.w_vza, psi=fn.w_psi, skyl=fn.w_skyl,
leaf_spectrum=fixed(w_rho_leaf), soil_spectrum=fixed(w_rho_soi... | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Recuerda en la [práctica sobre la radiación neta](./ES_radiacion_neta.ipynb) que una superficie vegetal tiene ciertas propiedades anisotrópicas, lo que quiere decir que reflejará de manera distinta según la geometria de iluminación y de observación. Mira cómo cambia el espectro variando los valores del ángulo de observ... | w_sensitivity = interactive(fn.prosail_sensitivity,
N_leaf=fn.w_nleaf, Cab=fn.w_cab, Car=fn.w_car, Ant=fn.w_ant, Cbrown=fn.w_cbrown,
Cw=fn.w_cw, Cm=fn.w_cm, lai=fn.w_lai, hotspot=fn.w_hotspot, leaf_angle=fn.w_leaf_angle,
sza=fn.w_sza,... | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Empieza con al sensiblidad del espectro a la concentración de clorofila. Verás que la zona donde sobre todo hay variaciones es en el verde y el rojo. Observa también que en el *red-edge*, la zona de transición entre el rojo y el NIR, se produce un "desplazamiento" de la señal, este fenómento es clave y es la razón por... | w_rho_sensor = interactive(fn.sensor_sensitivity,
sensor=fn.w_sensor, spectra=fixed(w_sensitivity))
display(w_rho_sensor) | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Realiza de nuevo un análisis de sensibilidad para la clorofila y compara la respuesta espectral que daría Landsat, Sentinel-2 y una camára UAV Derivación de parámetros de la vegetaciónHasta ahora hemos visto cómo el espectro de la superficie varía con respecto a los distintos parámetros biofísicos.Sin embargo, nuestro... | w_rho_sensor = interactive(fn.build_random_simulations, {"manual": True, "manual_name": "Generar simulaciones"},
n_sim=fixed(5000), n_leaf_range=fn.w_range_nleaf,
cab_range=fn.w_range_cab, car_range=fn.w_range_car,
ant_range=fn.w_range_ant... | _____no_output_____ | CC0-1.0 | ES_espectro_vegetacion.ipynb | hectornieto/Curso-WUE |
Detecting sound sources in YouTube videos First load all dependencies and set work and data paths | # set plotting parameters
%matplotlib inline
import matplotlib.pyplot as plt
# change notebook settings for wider screen
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
# For embedding YouTube videos in Ipython Notebook
from IPython.display import Yo... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Download model parameters and PCA embedding | if not os.path.isfile(os.path.join('src', 'audioset_demos', 'vggish_model.ckpt')):
urllib.request.urlretrieve(
"https://storage.googleapis.com/audioset/vggish_model.ckpt",
filename=os.path.join('src', 'audioset_demos', 'vggish_model.ckpt')
)
if not os.path.isfile(os.path.join('src', 'audioset_d... | (1, 527)
display_name prob
0 Speech 0.865663
506 Inside, small room 0.050520
1 Male speech, man speaking 0.047573
5 Narration, monologue 0.047426
46 Snort 0.043561
482 Ping 0.025956
354 ... | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Parameters for how to plot audio | # Sample rate
# this has to be at least twice of max frequency which we've entered
# but you can play around with different sample rates and see how this
# affects the results;
# since we generated this audio, the sample rate is the bitrate
sample_rate = vggish_params.SAMPLE_RATE
# size of audio FFT window relative to... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Choosing video IDs and start times before download | video_ids = [
'BaW_jenozKc',
'E6sS2d-NeTE',
'xV0eTva6SKQ',
'2Szah76TMgo',
'g38kRk6YAA0',
'OkkkPAE9KvE',
'N1zUp9aPFG4'
]
video_start_time_str = [
'00:00:00',
'00:00:10',
'00:00:05',
'00:00:02',
'00:03:10',
'00:00:10',
'00:00:06'
]
video_start_time = list(map(time_... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Download, save and cut video audio | video_titles = []
maxv = np.iinfo(np.int16).max
for i, vid in enumerate(video_ids):
# Download and store video under data/raw/
video_title = dl_yt.download_youtube_wav(
video_id=vid,
raw_dir=raw_dir,
short_raw_dir=short_raw_dir,
start_sec=video_start_time[i],
duration=d... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Retrieve VGGish PCA embeddings | video_vggish_emb = []
# Restore VGGish model trained on YouTube8M dataset
# Retrieve PCA-embeddings of bottleneck features
with tf.Graph().as_default(), tf.Session() as sess:
# Define the model in inference mode, load the checkpoint, and
# locate input and output tensors.
vggish_slim.define_vggish_slim(tra... | INFO:tensorflow:Restoring parameters from vggish_model.ckpt
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
(10, 96, 64)
(10, 128)
(10, 128)
7
| Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Plot audio, transformations and embeddings Function for visualising audio | def plot_audio(audio, emb):
audio_sec = audio.shape[0]/sample_rate
# Make a new figure
plt.figure(figsize=(18, 16), dpi= 60, facecolor='w', edgecolor='k')
plt.subplot(511)
# Display the spectrogram on a mel scale
librosa.display.waveplot(audio, int(sample_rate), max_sr = int(sample_rate))
pl... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Visualise all clips of audio chosen | for i, vid in enumerate(video_ids):
print("\nAnalyzing audio from video with title:\n", video_titles[i])
audio_path = os.path.join(short_raw_dir, vid) + '.wav'
# audio is a 1D time series of the sound
# can also use (audio, fs) = soundfile.read(audio_path)
(audio, fs) = librosa.load(
a... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Visualise one clip of audio and embed YouTube video for comparison | i = 4
vid = video_ids[i]
audio_path = os.path.join(raw_dir, vid) + '.wav'
# audio is a 1D time series of the sound
# can also use (audio, fs) = soundfile.read(audio_path)
(audio, fs) = librosa.load(
audio_path,
sr = sample_rate,
offset = video_start_time[i],
duration = duration
)
plot_audio(audio... | /usr/local/anaconda3/envs/audioset_tensorflow/lib/python3.6/site-packages/librosa/filters.py:284: UserWarning: Empty filters detected in mel frequency basis. Some channels will produce empty responses. Try increasing your sampling rate (and fmax) or reducing n_mels.
warnings.warn('Empty filters detected in mel freque... | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Evaluate trained audio detection model | import audio_event_detection_model as AEDM
import utilities
from sklearn import metrics
model = AEDM.CRNN_audio_event_detector()
| _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Evaluating model on audio downloaded | (x_user_inp, y_user_inp) = utilities.transform_data(
np.array(video_vggish_emb)
)
predictions = model.predict(
x=x_user_inp
) | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Evaluating model on training data | (x_tr, y_tr, vid_tr) = load_data(os.path.join(audioset_data_path, 'bal_train.h5'))
(x_tr, y_tr) = utilities.transform_data(x_tr, y_tr)
pred_tr = model.predict(x=x_tr)
print(pred_tr.max())
print(metrics.accuracy_score(y_tr, (pred_tr > 0.5).astype(np.float32)))
print(metrics.roc_auc_score(y_tr, pred_tr))
print(np.mean... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Investigating model predictions on downloaded audio clips | i = 0
vid = video_ids[i]
print(video_titles[i])
print()
YouTubeVideo(
vid,
start=start,
end=start+duration,
autoplay=0,
theme="light",
color="red"
)
example = pd.DataFrame(class_labels['display_name'][max_prob_classes[i,:10]])
example.loc[:, 'prob'] = pd.Series(max_prob[i, :10], index=example.... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
1. Understand attention2. Understand filters3. Understand Multi-label, hierachical, knowledge graphs4. Understand class imbalance 5. CCA on VGGish vs. ResNet audioset emb. to check if there's a linear connection. 6. Train linear layer to convert VGGish emb. to ResNet-50 emb. Plot in GUI:1. Exclude all non-active class... | video_vggish_emb = []
test_wav_path = os.path.join(src_dir, 'data', 'wav_file')
wav_files = os.listdir(test_wav_path)
example_names = []
# Restore VGGish model trained on YouTube8M dataset
# Retrieve PCA-embeddings of bottleneck features
with tf.Graph().as_default(), tf.Session() as sess:
# Define the model in inf... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
2018Q1Q10Q17Q12Q59Q512440Q-5889Q.wav2018Q1Q10Q13Q52Q8Q512440Q-5889Q.wav2018Q1Q10Q13Q29Q46Q512440Q-5889Q.wav2018Q1Q10Q17Q58Q49Q512348Q-5732Q.wav | for i, vid in enumerate(example_names):
print(vid)
print()
example = pd.DataFrame(class_labels['display_name'][max_prob_classes_AEDM[i,:10]])
example.loc[:, 'top_10_AEDM_pred'] = pd.Series(max_prob_AEDM[i, :10], index=example.index)
example.loc[:, 'index_ASC'] = pd.Series(max_prob_classes_ASC[i,:10]... | _____no_output_____ | Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Audio set data collection pipeline Download, cut and convert the audio of listed urls | colnames = '# YTID, start_seconds, end_seconds, positive_labels'.split(', ')
print(colnames)
bal_train_csv = pd.read_csv('balanced_train_segments.csv', sep=', ', header=2) #usecols=colnames)
bal_train_csv.rename(columns={colnames[0]: colnames[0][-4:]}, inplace=True)
print(bal_train_csv.columns.values)
print(bal_train_c... |
Loading VGGish base model:
| Apache-2.0 | notebooks/experiments/Sound Demo 3 - Multi-label classifier pretrained on audioset.ipynb | fronovics/AI_playground |
Gradient Descent Algorithm Implementation
* Tutorial: https://towardsai.net/p/data-science/gradient-descent-algorithm-for-machine-learning-python-tutorial-ml-9ded189ec556
* Github: https://github.com/towardsai/tutorials/tree/master/gradient_descent_tutorial | #Download the dataset
!wget https://raw.githubusercontent.com/towardsai/tutorials/master/gradient_descent_tutorial/data.txt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
column_names = ['Population', 'Profit']
df = pd.read_csv('data.txt', header=None, names=column_name... | _____no_output_____ | MIT | gradient_descent_tutorial/gradient_descent_tutorial.ipynb | fimoziq/tutorials |
**Error before applying Gradient Descent** | error = calculate_RSS(X, Y, theta)
error | _____no_output_____ | MIT | gradient_descent_tutorial/gradient_descent_tutorial.ipynb | fimoziq/tutorials |
**Apply Gradient Descent** | g, cost = gradientDescent(X, Y, theta, 0.01, 1000)
g | _____no_output_____ | MIT | gradient_descent_tutorial/gradient_descent_tutorial.ipynb | fimoziq/tutorials |
**Error after Applying Gradient Descent** | error = calculate_RSS(X, Y, g)
error
x = np.linspace(df.Population.min(), df.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(df.Population, df.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Popula... | _____no_output_____ | MIT | gradient_descent_tutorial/gradient_descent_tutorial.ipynb | fimoziq/tutorials |
if you wish to set which cores to useaffinity_mask = {4, 5, 7} affinity_mask = {6, 7, 9} affinity_mask = {0, 1, 3} affinity_mask = {2, 3, 5} affinity_mask = {0, 2, 4, 6} pid = 0os.sched_setaffinity(pid, affinity_mask) print("CPU affinity mask is modified to %s for process id 0" % affinity_mask) DEFAULT 'CarRacing-v3... | ## Choose one agent, see Docu for description
#agent='CarRacing-v0'
#agent='CarRacing-v1'
agent='CarRacing-v3'
# Stop training when the model reaches the reward threshold
callback_on_best = StopTrainingOnRewardThreshold(reward_threshold = 170, verbose=1)
seed = 2000
## SIMULATION param
## Changing these makes world... | _____no_output_____ | MIT | examples/Train_ppo_cnn+eval_contact-(pretrained).ipynb | pleslabay/CarRacing-mod |
Connect to Chicago Data Portal API - Business Licenses Data | #Import dependencies
import pandas as pd
import requests
import json
# Google developer API key
from config2 import API_chi_key
# Build API URL
# API calls = 8000 (based on zipcode and issued search results)
# Filters: 'application type' Issued
target_URL = f"https://data.cityofchicago.org/resource/xqx5-8hwx.json?$$ap... | _____no_output_____ | CNRI-Python | API_Chi_Busi_Licences.ipynb | oimartin/Real_Tech_Influence |
Connect to sqlite database | # Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from config2 import mysql_password
# Declare a Base using `automap_base()`
Base = automap_base()
# Create engine using the `demographics.sqlite` database file
# engine... | _____no_output_____ | CNRI-Python | API_Chi_Busi_Licences.ipynb | oimartin/Real_Tech_Influence |
Tutorial 1: Bayes with a binary hidden state**Week 3, Day 1: Bayesian Decisions****By Neuromatch Academy**__Content creators:__ [insert your name here]__Content reviewers:__ Tutorial ObjectivesThis is the first in a series of two core tutorials on Bayesian statistics. In these tutorials, we will explore the fundeme... | #@title Video 1: Introduction to Bayesian Statistics
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='JiEIn9QsrFg', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Setup Please execute the cells below to initialize the notebook environment. | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
from matplotlib import transforms
from matplotlib import gridspec
from scipy.optimize import fsolve
from collections import namedtuple
#@title Figure Settings
import ipywidgets as widgets # interactive display
from ipywidgets impor... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
--- Section 1: Gone Fishin' | #@title Video 2: Gone Fishin'
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='McALsTzb494', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
You were just introduced to the **binary hidden state problem** we are going to explore. You need to decide which side to fish on. We know fish like to school together. On different days the school of fish is either on the left or right side, but we don’t know what the case is today. We will represent our knowledge pro... | #@title Video 3: Utility
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='xvIVZrqF_5s', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
You know the probability that the school of fish is on the left side of the dock today, $P(s = left)$. You also know the probability that it is on the right, $P(s = right)$, because these two probabilities must add up to 1. You need to decide where to fish. It may seem obvious - you could just fish on the side where th... | # @markdown Execute this cell to use the widget
ps_widget = widgets.FloatSlider(0.9, description='p(s = left)', min=0.0, max=1.0, step=0.01)
@widgets.interact(
ps = ps_widget,
)
def make_utility_plot(ps):
fig = plot_utility(ps)
plt.show(fig)
plt.close(fig)
return None
# to_remove explanation
# 1) ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
In this section, you have seen that both the utility of various state and action pairs and our knowledge of the probability of each state affects your decision. Importantly, we want our knowledge of the probability of each state to be as accurate as possible! So how do we know these probabilities? We may have prior kno... | #@title Video 4: Likelihood
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='l4m0JzMWGio', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
First, we'll think about what it means to take a measurement (also often called an observation or just data) and what it tells you about what the hidden state may be. Specifically, we'll be looking at the **likelihood**, which is the probability of your measurement ($m$) given the hidden state ($s$): $P(m | s)$. Rememb... | #to_remove explanation
# 1) The fisherperson is on the left side so:
# - P(m = catch fish | s = left) = 0.7 because they have a 70% chance of catching
# a fish when on the same side as the school
# - P(m = no fish | s = left) = 0.3 because the probability of catching a fish
# and not catchi... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
In the prior exercise, you guessed where the school of fish was based on the measurement you took (watching someone fish). You did this by choosing the state (side of school) that maximized the probability of the measurement. In other words, you estimated the state by maximizing the likelihood (had the highest probabil... | #@title Video 5: Correlation and marginalization
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='vsDjtWi-BVo', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
In this section, we are going to take a step back for a bit and think more generally about the amount of information shared between two random variables. We want to know how much information you gain when you observe one variable (take a measurement) if you know something about another. We will see that the fundamental... | # to_remove explanation
# 1) The probability of a fish being silver is the joint probability of it being
#. small and silver plus the joint probability of it being large and silver:
#
#. P(Y = silver) = P(X = small, Y = silver) + P(X = large, Y = silver)
#. = 0.4 + 0.1
#. = 0.5
# 2) This is all the po... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Think! 4: Covarying probability distributionsThe relationship between the marginal probabilities and the joint probabilities is determined by the correlation between the two random variables - a normalized measure of how much the variables covary. We can also think of this as gaining some information about one of the ... | # @markdown Execute this cell to enable the widget
style = {'description_width': 'initial'}
gs = GridspecLayout(2,2)
cor_widget = widgets.FloatSlider(0.0, description='ρ', min=-1, max=1, step=0.01)
px_widget = widgets.FloatSlider(0.5, description='p(color=golden)', min=0.01, max=0.99, step=0.01, style=style)
py_widget... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
We have just seen how two random variables can be more or less independent. The more correlated, the less independent, and the more shared information. We also learned that we can marginalize to determine the marginal likelihood of a hidden state or to find the marginal probability distribution of two random variables.... | # to_remove explanation
# 1. Using Bayes rule, we know that P(s = left | m = catch fish) = P(m = catch fish | s = left)P(s = left) / P(m = catch fish)
#. Let's first compute P(m = catch fish):
#. P(m = catch fish) = P(m = catch fish | s = left)P(s = left) + P(m = catch fish | s = right)P(s = right)
# ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Coding Exercise 5: Computing PosteriorsLet's implement our above math to be able to compute posteriors for different priors and likelihood.sAs before, our prior is $p(s = left) = 0.3$ and $p(s = right) = 0.7$. In the video, we learned that the chance of catching a fish given they fish on the same side as the school wa... | def compute_posterior(likelihood, prior):
""" Use Bayes' Rule to compute posterior from likelihood and prior
Args:
likelihood (ndarray): i x j array with likelihood probabilities where i is
number of state options, j is number of measurement options
prior (ndarray): i x 1 array with pri... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Interactive Demo 5: What affects the posterior?Now that we can understand the implementation of *Bayes rule*, let's vary the parameters of the prior and likelihood to see how changing the prior and likelihood affect the posterior. In the demo below, you can change the prior by playing with the slider for $p( s = left)... | # @markdown Execute this cell to enable the widget
style = {'description_width': 'initial'}
ps_widget = widgets.FloatSlider(0.3, description='p(s = left)',
min=0.01, max=0.99, step=0.01)
p_a_s1_widget = widgets.FloatSlider(0.5, description='p(fish | s = left)',
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Section 6: Making Bayesian fishing decisionsWe will explore how to consider the expected utility of an action based on our belief (the posterior distribution) about where we think the fish are. Now we have all the components of a Bayesian decision: our prior information, the likelihood given a measurement, the posteri... | # @markdown Execute this cell to enable the widget
style = {'description_width': 'initial'}
ps_widget = widgets.FloatSlider(0.3, description='p(s)',
min=0.01, max=0.99, step=0.01)
p_a_s1_widget = widgets.FloatSlider(0.5, description='p(fish | s = left)',
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D1_BayesianDecisions/W3D1_Tutorial1.ipynb | bgalbraith/course-content |
Dependencies | # !pip install --quiet efficientnet
!pip install --quiet image-classifiers
import warnings, json, re, glob, math
from scripts_step_lr_schedulers import *
from melanoma_utility_scripts import *
from kaggle_datasets import KaggleDatasets
from sklearn.model_selection import KFold
import tensorflow.keras.layers as L
import... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
TPU configuration | strategy, tpu = set_up_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
AUTO = tf.data.experimental.AUTOTUNE | REPLICAS: 1
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model parameters | config = {
"HEIGHT": 256,
"WIDTH": 256,
"CHANNELS": 3,
"BATCH_SIZE": 64,
"EPOCHS": 25,
"LEARNING_RATE": 3e-4,
"ES_PATIENCE": 10,
"N_FOLDS": 5,
"N_USED_FOLDS": 5,
"TTA_STEPS": 25,
"BASE_MODEL": 'seresnet18',
"BASE_MODEL_WEIGHTS": 'imagenet',
"DATASET_PATH": 'melanoma-256x256'
}
with open('conf... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Load data | database_base_path = '/kaggle/input/siim-isic-melanoma-classification/'
k_fold = pd.read_csv(database_base_path + 'train.csv')
test = pd.read_csv(database_base_path + 'test.csv')
print('Train samples: %d' % len(k_fold))
display(k_fold.head())
print(f'Test samples: {len(test)}')
display(test.head())
GCS_PATH = KaggleD... | Train samples: 33126
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Augmentations | def data_augment(image, label):
p_spatial = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_spatial2 = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_rotate = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_crop = tf.random.uniform([1], minval=0, maxval=1, dtyp... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Auxiliary functions | # Datasets utility functions
def read_labeled_tfrecord(example, height=config['HEIGHT'], width=config['WIDTH'], channels=config['CHANNELS']):
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
image = decode_image(example['image'], height, width, channels)
label = tf.cast(example['target'],... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Learning rate scheduler | lr_min = 1e-6
# lr_start = 0
lr_max = config['LEARNING_RATE']
steps_per_epoch = 24844 // config['BATCH_SIZE']
total_steps = config['EPOCHS'] * steps_per_epoch
warmup_steps = steps_per_epoch * 5
# hold_max_steps = 0
# step_decay = .8
# step_size = steps_per_epoch * 1
# rng = [i for i in range(0, total_steps, 32)]
# y =... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model | # Initial bias
pos = len(k_fold[k_fold['target'] == 1])
neg = len(k_fold[k_fold['target'] == 0])
initial_bias = np.log([pos/neg])
print('Bias')
print(pos)
print(neg)
print(initial_bias)
# class weights
total = len(k_fold)
weight_for_0 = (1 / neg)*(total)/2.0
weight_for_1 = (1 / pos)*(total)/2.0
class_weight = {0: we... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Training | # Evaluation
eval_dataset = get_eval_dataset(TRAINING_FILENAMES, batch_size=config['BATCH_SIZE'], buffer_size=AUTO)
image_names = next(iter(eval_dataset.unbatch().map(lambda data, label, image_name: image_name).batch(count_data_items(TRAINING_FILENAMES)))).numpy().astype('U')
image_data = eval_dataset.map(lambda data, ... |
FOLD: 1
Downloading data from https://github.com/qubvel/classification_models/releases/download/0.0.1/seresnet18_imagenet_1000_no_top.h5
45359104/45351256 [==============================] - 4s 0us/step
Epoch 1/25
408/408 - 147s - loss: 0.7536 - auc: 0.7313 - val_loss: 0.1771 - val_auc: 0.5180
Epoch 2/25
408/408 - 144s... | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model loss graph | for n_fold in range(config['N_USED_FOLDS']):
print(f'Fold: {n_fold + 1}')
plot_metrics(history_list[n_fold]) | Fold: 1
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model loss graph aggregated | plot_metrics_agg(history_list, config['N_USED_FOLDS']) | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model evaluation (best) | display(evaluate_model(k_fold_best, config['N_USED_FOLDS']).style.applymap(color_map))
display(evaluate_model_Subset(k_fold_best, config['N_USED_FOLDS']).style.applymap(color_map)) | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Model evaluation (last) | display(evaluate_model(k_fold, config['N_USED_FOLDS']).style.applymap(color_map))
display(evaluate_model_Subset(k_fold, config['N_USED_FOLDS']).style.applymap(color_map)) | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Confusion matrix | for n_fold in range(config['N_USED_FOLDS']):
n_fold += 1
pred_col = f'pred_fold_{n_fold}'
train_set = k_fold_best[k_fold_best[f'fold_{n_fold}'] == 'train']
valid_set = k_fold_best[k_fold_best[f'fold_{n_fold}'] == 'validation']
print(f'Fold: {n_fold}')
plot_confusion_matrix(train_set['target'],... | Fold: 1
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Visualize predictions | k_fold['pred'] = 0
for n_fold in range(config['N_USED_FOLDS']):
k_fold['pred'] += k_fold[f'pred_fold_{n_fold+1}'] / config['N_FOLDS']
print('Label/prediction distribution')
print(f"Train positive labels: {len(k_fold[k_fold['target'] > .5])}")
print(f"Train positive predictions: {len(k_fold[k_fold['pred'] > .5])}")... | Label/prediction distribution
Train positive labels: 581
Train positive predictions: 2647
Train positive correct predictions: 578
Top 10 samples
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Visualize test predictions | print(f"Test predictions {len(test[test['target'] > .5])}|{len(test[test['target'] <= .5])}")
print(f"Test predictions (last) {len(test[test['target_last'] > .5])}|{len(test[test['target_last'] <= .5])}")
print('Top 10 samples')
display(test[['image_name', 'sex', 'age_approx','anatom_site_general_challenge', 'target',... | Test predictions 1506|9476
Test predictions (last) 1172|9810
Top 10 samples
| MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
Test set predictions | submission = pd.read_csv(database_base_path + 'sample_submission.csv')
submission['target'] = test['target']
submission['target_last'] = test['target_last']
submission['target_blend'] = (test['target'] * .5) + (test['target_last'] * .5)
display(submission.head(10))
display(submission.describe())
### BEST ###
submissi... | _____no_output_____ | MIT | Model backlog/Train/64-melanoma-5fold-seresnet18-radam.ipynb | dimitreOliveira/melanoma-classification |
CTA data analysis with Gammapy Introduction**This notebook shows an example how to make a sky image and spectrum for simulated CTA data with Gammapy.**The dataset we will use is three observation runs on the Galactic center. This is a tiny (and thus quick to process and play with and learn) subset of the simulated CTA... | %matplotlib inline
import matplotlib.pyplot as plt
!gammapy info --no-envvar --no-system
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.convolution import Gaussian2DKernel
from regions import CircleSkyRegion
from gammapy.modeling import Fit
from gammapy.data import Da... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Select observationsA Gammapy analysis usually starts by creating a `~gammapy.data.DataStore` and selecting observations.This is shown in detail in the other notebook, here we just pick three observations near the galactic center. | data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps")
# Just as a reminder: this is how to select observations
# from astropy.coordinates import SkyCoord
# table = data_store.obs_table
# pos_obs = SkyCoord(table['GLON_PNT'], table['GLAT_PNT'], frame='galactic', unit='deg')
# pos_target = SkyCoord(0, 0, fra... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Make sky images Define map geometrySelect the target position and define an ON region for the spectral analysis | axis = MapAxis.from_edges(
np.logspace(-1.0, 1.0, 10), unit="TeV", name="energy", interp="log"
)
geom = WcsGeom.create(
skydir=(0, 0), npix=(500, 400), binsz=0.02, frame="galactic", axes=[axis]
)
geom | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Compute imagesExclusion mask currently unused. Remove here or move to later in the tutorial? | target_position = SkyCoord(0, 0, unit="deg", frame="galactic")
on_radius = 0.2 * u.deg
on_region = CircleSkyRegion(center=target_position, radius=on_radius)
exclusion_mask = geom.to_image().region_mask([on_region], inside=False)
exclusion_mask = WcsNDMap(geom.to_image(), exclusion_mask)
exclusion_mask.plot();
%%time
st... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Show imagesLet's have a quick look at the images we computed ... | dataset_image.counts.smooth(2).plot(vmax=5);
dataset_image.background.plot(vmax=5);
dataset_image.excess.smooth(3).plot(vmax=2); | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Source DetectionUse the class `~gammapy.estimators.TSMapEstimator` and function `gammapy.estimators.utils.find_peaks` to detect sources on the images. We search for 0.1 deg sigma gaussian sources in the dataset. | spatial_model = GaussianSpatialModel(sigma="0.05 deg")
spectral_model = PowerLawSpectralModel(index=2)
model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)
ts_image_estimator = TSMapEstimator(
model,
kernel_width="0.5 deg",
selection_optional=[],
downsampling_factor=2,
sum_ov... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Spatial analysisSee other notebooks for how to run a 3D cube or 2D image based analysis. SpectrumWe'll run a spectral analysis using the classical reflected regions background estimation method,and using the on-off (often called WSTAT) likelihood function. | energy_axis = MapAxis.from_energy_bounds(0.1, 40, 40, unit="TeV", name="energy")
energy_axis_true = MapAxis.from_energy_bounds(
0.05, 100, 200, unit="TeV", name="energy_true"
)
geom = RegionGeom.create(region=on_region, axes=[energy_axis])
dataset_empty = SpectrumDataset.create(
geom=geom, energy_axis_true=ener... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Model fitThe next step is to fit a spectral model, using all data (i.e. a "global" fit, using all energies). | %%time
spectral_model = PowerLawSpectralModel(
index=2, amplitude=1e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV
)
model = SkyModel(spectral_model=spectral_model, name="source-gc")
datasets.models = model
fit = Fit(datasets)
result = fit.run()
print(result) | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Spectral pointsFinally, let's compute spectral points. The method used is to first choose an energy binning, and then to do a 1-dim likelihood fit / profile to compute the flux and flux error. | # Flux points are computed on stacked observation
stacked_dataset = datasets.stack_reduce(name="stacked")
print(stacked_dataset)
energy_edges = MapAxis.from_energy_bounds("1 TeV", "30 TeV", nbin=5).edges
stacked_dataset.models = model
fpe = FluxPointsEstimator(energy_edges=energy_edges, source="source-gc")
flux_poin... | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
PlotLet's plot the spectral model and points. You could do it directly, but for convenience we bundle the model and the flux points in a `FluxPointDataset`: | flux_points_dataset = FluxPointsDataset(data=flux_points, models=model)
flux_points_dataset.plot_fit(); | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Exercises* Re-run the analysis above, varying some analysis parameters, e.g. * Select a few other observations * Change the energy band for the map * Change the spectral model for the fit * Change the energy binning for the spectral points* Change the target. Make a sky image and spectrum for your favourit... | # print('hello world')
# SkyCoord.from_name('crab') | _____no_output_____ | BSD-3-Clause | docs/tutorials/cta_data_analysis.ipynb | Jaleleddine/gammapy |
Vuoi conoscere gli incendi divampati dopo il 15 settembre 2019? | mes = australia_1[(australia_1["acq_date"]>= "2019-09-15")]
mes.head()
mes.describe()
map_sett = folium.Map([-25.274398,133.775136], zoom_start=4)
lat_3 = mes["latitude"].values.tolist()
long_3 = mes["longitude"].values.tolist()
australia_cluster_3 = MarkerCluster().add_to(map_sett)
for lat_3,long_3 in zip(lat_3,long_3... | _____no_output_____ | BSD-3-Clause | courses/08_Plotly_Bokeh/Fire_Australia19.ipynb | visiont3lab/data-visualization |
Play with Folium | 44.4807035,11.3712528
import folium
m1 = folium.Map(location=[44.48, 11.37], tiles='openstreetmap', zoom_start=18)
m1.save('map1.html')
m1
m3.save("filename.png")
| _____no_output_____ | BSD-3-Clause | courses/08_Plotly_Bokeh/Fire_Australia19.ipynb | visiont3lab/data-visualization |
from google.colab import drive
drive.mount('/content/drive') | Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
| MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 | |
CombineInator (parent class) | class CombineInator:
def __init__(self):
self.source = ""
def translate_model(self, source):
if source == "en":
tokenizer_trs = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-trk")
model_trs = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-en-trk")
pipe_trs = "t... | _____no_output_____ | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
WikiWebScraper (child) | import requests
import re
from bs4 import BeautifulSoup
from tqdm import tqdm
from os.path import exists, basename, splitext
class WikiWebScraper(CombineInator):
def __init__(self):
self.__HEADERS_PARAM = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gec... | _____no_output_____ | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Örnek kullanım | library = WikiWebScraper()
PATH = "/content/"
library.categorical_scraper("savaş", PATH, 20, text_into_sentences_param=False) | Sayfa taranıyor.: 100%|██████████| 20/20 [00:00<00:00, 52.99it/s]
Sayfa Ayrıştırılıyor: 100%|██████████| 20/20 [00:04<00:00, 4.68it/s] | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
speechModule (child) | !pip install transformers
!pip install simpletransformers
from os import path
from IPython.display import Audio
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM, Wav2Vec2Processor, Wav2Vec2ForCTC
import librosa
import torch
class speechModule(CombineInator):
def __init__(self):
self.SAMPLI... | _____no_output_____ | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Örnek kullanım | filename = "_path_to_wav_file" # ses dosyası pathi verilmelidir
speechM = speechModule()
speechM.get_repo()
speechM.speech2text2trans2speech(filename, "tr", "speech") | _____no_output_____ | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Lxmert (child) | !git clone https://github.com/hila-chefer/Transformer-MM-Explainability
import os
os.chdir(f'./Transformer-MM-Explainability')
!pip install -r requirements.txt
%cd Transformer-MM-Explainability
from lxmert.lxmert.src.modeling_frcnn import GeneralizedRCNN
import lxmert.lxmert.src.vqa_utils as utils
from lxmert.lxmert.... | _____no_output_____ | MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Örnek kullanım | lxmert = Lxmert()
PATH = '_path_to_jpg_' # jpg dosyası pathi verilmelidir
turkce_soru = 'Resimde neler var'
lxmert.resim_uzerinden_soru_cevap(PATH, turkce_soru) | loading configuration file cache
loading weights file https://cdn.huggingface.co/unc-nlp/frcnn-vg-finetuned/pytorch_model.bin from cache at /root/.cache/torch/transformers/57f6df6abe353be2773f2700159c65615babf39ab5b48114d2b49267672ae10f.77b59256a4cf8343ae0f923246a81489fc8d82f98d082edc2d2037c977c0d9d0
| MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Web Arayüz | !pip install flask-ngrok
from flask import Flask, redirect, url_for, render_template, request, flash
from flask_ngrok import run_with_ngrok
# Burada web_dependencies klasörü içerisinde bulunan klasörlerin pathi verilmelidir.
template_folder = '_path_to_templates_folder_'
static_folder = '_path_to_static_folder_'
app = ... | * Serving Flask app "__main__" (lazy loading)
* Environment: production
[31m WARNING: This is a development server. Do not use it in a production deployment.[0m
[2m Use a production WSGI server instead.[0m
* Debug mode: off
| MIT | Combineinator_Library.ipynb | combineinator/combine-inator-acikhack2021 |
Reflect Tables into SQLAlchemy ORM | # Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_bas... | _____no_output_____ | ADSL | climate_starter.ipynb | gracesco/HuefnerSQLAlchemyChallenge |
Exploratory Climate Analysis | # Design a query to retrieve the last 12 months of precipitation data and plot the results
CY_precipitation = session.query(Measurements.date).filter(Measurements.date >= "2016-08-23").order_by(Measurements.date).all()
# # Calculate the date 1 year ago from the last data point in the database
LY_precipitation = session... | _____no_output_____ | ADSL | climate_starter.ipynb | gracesco/HuefnerSQLAlchemyChallenge |
Import dataset | bd=pd.read_csv('creditcard.csv')
bd.head() | _____no_output_____ | Unlicense | Credit card fraud .ipynb | Boutayna98/Credit-Card-Fraud-Detection |
Exploring dataset | bd.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 284807 entries, 0 to 284806
Data columns (total 31 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Time 284807 non-null float64
1 V1 284807 non-null float64
2 V2 284807 non-null float64
3 V3 284807... | Unlicense | Credit card fraud .ipynb | Boutayna98/Credit-Card-Fraud-Detection |
Pre processing | sc = StandardScaler()
amount = bd['Amount'].values
bd['Amount'] = sc.fit_transform(amount.reshape(-1, 1))
bd.drop(['Time'], axis=1, inplace=True)
bd.shape
bd.drop_duplicates(inplace=True)
bd.shape | _____no_output_____ | Unlicense | Credit card fraud .ipynb | Boutayna98/Credit-Card-Fraud-Detection |
Modelling | X = bd.drop('Class', axis = 1).values
y = bd['Class'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 1)
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, export_graphviz, export
DT = DecisionTreeClassifier(max_depth = 4, criterion = 'entropy')
DT.... | _____no_output_____ | Unlicense | Credit card fraud .ipynb | Boutayna98/Credit-Card-Fraud-Detection |
Exploratory data analysis | # import libraries
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 500)
%matplotlib inline
# load the processed data
main_df = pd.read_csv('../data/processed/COVID_small_table_confirmed.csv', sep=';')
main_df.head()
main_df.info... | Running on http://127.0.0.1:8050/
Running on http://127.0.0.1:8050/
Debugger PIN: 839-733-624
Debugger PIN: 839-733-624
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug m... | FTL | notebooks/Data_EDA.ipynb | Prudhvi-Kumar-Kakani/Data-Science-CRISP-DM--Covid-19 |
2+3+
for r in range(n):
sumaRenglon=0
sumaRenglon=0
sumaRenglon=0
for c in range(n):
sumaRenglon +=a2d.get_item(r,c)
total += a2d.get_item(r,c)
def ejemplo1( n ):
c = n + 1
d = c * n
e = n * n
total = c + e - d
print(f"total={ total }")
ejemplo1( 99999 )
def ejemplo2( n ):
contad... | _____no_output_____ | MIT | 21octubre.ipynb | humbertoguell/daa2020_1 | |
Naive Bayes Classifiers Author : Sanjoy Biswas Topic : NaiveNaive Bayes Classifiers : Spam Ham Email Datection Email : sanjoy.eee32@gmail.com It is a classification technique based on Bayes’ Theorem with an assumption of independence among predictors. In simple terms, a Naive Bayes classifier assumes that the pre... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Import Dataset | df = pd.read_csv(r'F:\ML Algorithms By Me\Naive Bayes Classifiers\emails.csv')
df.head()
df.isnull().sum() | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Separate Dependent & Independent Value | x = df.text.values
y = df.spam.values | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Split Train and Test Dataset | from sklearn.model_selection import train_test_split
xtrain,xtest,ytrain,ytest = train_test_split(x,y,test_size=0.3) | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Data Preprocessing | from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
x_train = cv.fit_transform(xtrain)
x_train.toarray() | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Apply Naive Bayes Classifiers Algorithm | from sklearn.naive_bayes import MultinomialNB
model = MultinomialNB()
model.fit(x_train,ytrain)
x_test = cv.fit_transform(xtest)
x_test.toarray()
model.score(x_train,ytrain) | _____no_output_____ | MIT | ML Algorithms/Naive Bayes Classifiers/Naive Bayes Classifiers.ipynb | jrderek/Data-science-master-resources |
Framing models | import lettertask
import patches
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from tqdm import tqdm
import lazytools_sflippl as lazytools
import plotnine as gg
import pandas as pd
cbm = lettertask.data.CompositionalBinaryModel(
width=[5, 5],
change_probability=[0.05, 0.5],
... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
Base-reconstructive model | class BaRec(nn.Module):
def __init__(self, latent_features, input_features=None, timesteps=None,
data=None, bias=True):
super().__init__()
if data:
input_features = input_features or data.n_vars
timesteps = timesteps or data.n_timesteps
elif input_fea... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.