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 |
|---|---|---|---|---|---|
Обработка пропусков | train_df.isnull().sum()
train_df[['Square', 'LifeSquare', 'KitchenSquare']].head(10) | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**LifeSquare** | # медиана до корректировки
train_df['LifeSquare'].median()
# медиана расхождения площадей
square_med_diff = (train_df.loc[train_df['LifeSquare'].notnull(), 'Square']
- train_df.loc[train_df['LifeSquare'].notnull(), 'LifeSquare']
- train_df.loc[train_df['LifeSquare'].notnull(), 'Kit... | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**Healthcare_1** | train_df['Healthcare_1'].head()
train_df.loc[train_df['Healthcare_1'].isnull(), 'Healthcare_1'] = train_df['Healthcare_1'].median() | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
Построение новых признаков **Dummies** | train_df['Ecology_2_bin'] = train_df['Ecology_2'].replace({'A':0, 'B':1})
train_df['Ecology_3_bin'] = train_df['Ecology_3'].replace({'A':0, 'B':1})
train_df['Shops_2_bin'] = train_df['Shops_2'].replace({'A':0, 'B':1}) | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**DistrictSize, IsDistrictLarge** | train_df['DistrictId'].value_counts()
district_size = train_df['DistrictId'].value_counts().reset_index()\
.rename(columns={'index':'DistrictId', 'DistrictId':'DistrictSize'})
district_size.head()
train_df = train_df.merge(district_size, on='DistrictId', how='left')
train_df.head()
(train_df['DistrictSi... | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**MedPriceByDistrict** | med_price_by_district = train_df.groupby(['DistrictId', 'Rooms'], as_index=False).agg({'Price':'median'})\
.rename(columns={'Price':'MedPriceByDistrict'})
med_price_by_district.head()
train_df = train_df.merge(med_price_by_district, on=['DistrictId', 'Rooms'], how='left')
train_df.head()
train_d... | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
*Пример переноса признака на test* | test_df['DistrictId'] = test_df['DistrictId'].astype(str)
test_df.merge(med_price_by_district, on=['DistrictId', 'Rooms'], how='left').info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 5000 entries, 0 to 4999
Data columns (total 20 columns):
Id 5000 non-null int64
DistrictId 5000 non-null object
Rooms 5000 non-null float64
Square 5000 non-null float64
LifeSquare 3959 non-null floa... | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
Отбор признаков | train_df.columns.tolist()
feature_names = ['Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear',
'Ecology_1', 'Ecology_2_bin', 'Ecology_3_bin', 'Social_1', 'Social_2', 'Social_3',
'Healthcare_1', 'Helthcare_2', 'Shops_1', 'Shops_2_bin']
new_feature_name... | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
Разбиение на train и val | X = train_df[feature_names + new_feature_names]
y = train_df[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, shuffle=True, random_state=21) | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
Построение модели **Обучение и оценка модели** | rf_model = RandomForestRegressor(random_state=21)
rf_model.fit(X_train, y_train) | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**Отложенная выборка** | y_train_preds = rf_model.predict(X_train)
y_test_preds = rf_model.predict(X_test)
evaluate_preds(y_train, y_train_preds, y_test, y_test_preds) | Train R2: 0.952
Valid R2: 0.671
| MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**Перекрёстная проверка** | cv_score = cross_val_score(rf_model, X, y, scoring='r2', cv=KFold(n_splits=3, shuffle=True, random_state=21))
cv_score
cv_score.mean() | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
XGBoost | from xgboost import XGBRegressor
xgb = xgboost.XGBRegressor(n_estimators=500, learning_rate=0.08, gamma=0, subsample=0.75,
colsample_bytree=1, max_depth=7, objective ='reg:squarederror')
xgb.fit(X_train, y_train)
y_train_preds = xgb.predict(X_train)
y_test_preds = xgb.predict(X_test)
evalu... | Train R2: 0.917
Test R2: 0.714
| MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
**Важность признаков** | feature_importances = pd.DataFrame(zip(X_train.columns, rf_model.feature_importances_),
columns=['feature_name', 'importance'])
feature_importances.sort_values(by='importance', ascending=False) | _____no_output_____ | MIT | Web06.ipynb | gera09/Numpy_Matplotlib_Scikit-learn |
Crear un subconjunto de datos | account_length = data["Account Length"]
account_length.head()
(type)(account_length)
subset = data[["Account Length", "Phone", "Eve Charge", "Day Calls"]]
subset.head()
desired_columns = ["Account Length", "Phone", "Eve Charge", "Night Calls"]
subset = data[desired_columns]
subset.head()
desired_columns = ["Account Len... | _____no_output_____ | MIT | notebooks/T2 -1 - Data Cleaning - Data Wrangling.ipynb | neovanorphen/data_science_course |
Generación de números aleatorios | import numpy as np
np.random.randint(1,100)
np.random.random()
def randint_list(n, a, b):
x = []
for i in range(n):
x.append(np.random.randint(a,b))
return x
randint_list(25, 1, 50)
import random
random.randrange(0,100,7)
a = np.arange(100)
a
np.random.shuffle(a)
a
col_list = data.columns.values.tol... | 0.8823493117539459
0.10432773786047767
0.9070093335163405
0.3063988986063515
0.446408872427422
| MIT | notebooks/T2 -1 - Data Cleaning - Data Wrangling.ipynb | neovanorphen/data_science_course |
Radial Velocity Orbit-fitting with RadVel Week 6, Intro-to-Astro 2021 Written by Ruben Santana & Sarah Blunt, 2018 Updated by Joey Murphy, June 2020 Updated by Corey Beard, July 2021 Background informationRadial velocity measurements tell us how the velocity of a star changes along the direction of our line of sight. ... | # allows us to see plots on the jupyter notebook
%matplotlib inline
# used to interact with operating system
import os
# models used by radvel for calculations, plotting, and model optimization
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import optimize
# for c... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
2. Importing and Plotting DataWhen you installed RadVel, some .csv files were placed in a directory on your computer called `radvel.DATADIR`. Let's read this data into Python using pandas. | # import data
path = os.path.join(radvel.DATADIR,'epic203771098.csv') # path to data file
data = pd.read_csv(path, index_col=0) # read data into pandas DataFrame
print('Path to radvel.DATADIR: {}\n'.format(radvel.DATADIR))
print(data)
# Let's print out the column names of the pandas DataFrame you just created (`... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
3. Finding a Significant Period Now, we will find probable orbital periods using a Lomb-Scargle periodogram. Periodograms are created using a Fourier transform, which is a mathematical process that takes in continuous time-based data and decomposes it into a combination of functions with various frequencies, as seen i... | def LombScarg(t,v,e,min_per=0.01,max_per=1000):
#Calculate Generalized Lomb-Scargle periodogram and window function
fmin = 1./max_per
fmax = 1./min_per
frequency, power = LombScargle(t, v, e).autopower(minimum_frequency=1/1000,maximum_frequency=1.,method='cython')
per = 1/frequency
#Identify ... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
4. Defining and Initializing Model Let's define a function that we will use to initialize the ``radvel.Parameters`` and ``radvel.RVModel`` objects.These will be our initial guesses of the planet parameters based on on the radial velocity measurements shown and periodogram shown above. | nplanets = 1 # number of planets
def initialize_model():
time_base = 2420.
params = radvel.Parameters(nplanets,basis='per tc secosw sesinw k')
params['per1'] = radvel.Parameter(value=period1) # Insert our guess for period of first planet (from periodogram)
params['tc1'] = radvel.Parameter(va... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Fit the K2-24 RV data assuming circular orbits.Set initial guesses for the parameters: | mod = initialize_model() # model initiliazed
like = radvel.likelihood.RVLikelihood(mod, data.t, data.vel, data.errvel, '_HIRES') # initialize Likelihood object
# define initial guesses for instrument-related parameters
like.params['gamma_HIRES'] = radvel.Parameter(value=0.1) # zero-point radial velocity offset
like.pa... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Plot the model with our initial parameter guesses: | def plot_results(like):
fig = plt.figure(figsize=(12,4))
fig = plt.gcf()
fig.set_tight_layout(True)
plt.errorbar(
like.x, like.model(data.t.values)+like.residuals(),
yerr=like.yerr, fmt='o'
)
ti = np.linspace(data.t.iloc[0] - 5, data.t.iloc[-1] + 5,100) # time array for... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
5. Maximum Likelihood fit Well, that solution doesn't look very good! Let's optimize the parameters set to vary by maximizing the likelihood.Initialize a ``radvel.Posterior`` object. | post = radvel.posterior.Posterior(like) # initialize radvel.Posterior object | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Choose which parameters to change or hold fixed during a fit. By default, all `radvel.Parameter` objects will vary, so you only have to worry about setting the ones you want to hold fixed. | post.likelihood.params['secosw1'].vary = False # set as false because we are assuming circular orbit
post.likelihood.params['sesinw1'].vary = False # set as false because we are assuming circular orbit
print(like) | parameter value vary
per1 43.8487 True
tc1 2080 True
secosw1 0 False
sesinw1 0 False
k1 3 True
dvdt -0.02 ... | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Maximize the likelihood and print the updated posterior object | res = optimize.minimize(
post.neglogprob_array, # objective function is negative log likelihood
post.get_vary_params(), # initial variable parameters
method='Powell', # Nelder-Mead also works
)
plot_results(like) # plot best fit model
print(post) | parameter value vary
per1 49.0164 True
tc1 2080.57 True
secosw1 0 False
sesinw1 0 False
k1 3.81242 True
dvdt -0.0843784 ... | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
RadVel comes equipped with some fancy ready-made plotting routines. Check this out! | matplotlib.rcParams['font.size'] = 12
RVPlot = orbit_plots.MultipanelPlot(post)
RVPlot.plot_multipanel()
matplotlib.rcParams['font.size'] = 18 | NOTE: This version of radvel has been modified to NOT include jitters in errorbars.
| MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
6. Residuals and RepeatResiduals are the difference of our data and our best-fit model. Next, we will plot the residuals of our optimized model to see if there is a second planet in our data. When we look at the following residuals, we will see a sinusoidal shape, so another planet may be present! Thus, we will repeat... | residuals1 = post.likelihood.residuals()
# Let's make a plot of data.time versus `residuals1`
plt.figure()
plt.scatter(data.t, residuals1)
plt.xlabel('time [MJD]')
plt.ylabel('RV [m/s]')
plt.show()
# TODO: What do you notice? What would you estimate the period
# of the other exoplanet in this system to be? Write you... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Let's repeat the above analysis with two planets! | nyquist = 2 # maximum sampling rate
minPer = 20 # minimum period to look for 2nd planet
maxPer = 30 # max period to look for 2nd planet
# finding 2nd planet period
period, power, period2 = LombScarg(data.t, data.vel, data.errvel, min_per=minPer, max_per=maxPer) # finding possible periords for 2nd planet
period, power... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Repeat the RadVel analysis | nplanets = 2 # number of planets
def initialize_model():
time_base = 2420
params = radvel.Parameters(nplanets,basis='per tc secosw sesinw k')
# 1st Planet
params['per1'] = post.params['per1'] # period of 1st planet
params['tc1'] = post.params['tc1'] # time transit of 1st planet
... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
K2-24 only has two known exoplanets so will stop this part of our analysis here. However, when analzying an uncharacterized star system, it's important to continue the analysis until we see no significant reduction in the residuals of the radial velocity. 7. Markov Chain Monte Carlo (MCMC)After reading the intro to M... | # TODO: edit the Markdown cell immediately above this one with a 3 sentence description of the MCMC method.
# What does MCMC do? Why do you think it is important to use MCMC to characterize uncertainties in radial
# velocity fits? | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Let's use RadVel to perform an MCMC fit: | df = radvel.mcmc(post, nwalkers=50, nrun=1000)
# TODO: What type of data structure is `df`, the object returned by RadVel's MCMC method?
"""
It is a pandas dataframe
""" | 20000/400000 (5.0%) steps complete; Running 15855.08 steps/s; Mean acceptance rate = 48.2%; Min Auto Factor = 19; Max Auto Relative-Change = inf; Min Tz = 6614.6; Max G-R = 1.004
Discarding burn-in now that the chains are marginally well-mixed
400000/400000 (100.0%) steps complete; Running 15030.55 steps/s; Mean ac... | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
Make a fun plot! | Corner = mcmc_plots.CornerPlot(post, df)
Corner.plot()
# TODO: There is a lot going on in this plot. What do you think the off-diagonal boxes are showing?
# What about the on-diagonal boxes? What is the median period of the first planet?
# What is the uncertainty on the period of the first planet? The second plane... | _____no_output_____ | MIT | Week6_radvel_fitting/Key.ipynb | chetanchawla/Intro-to-Astro-2021 |
2019-07-28* Got some framework up to do coupling layers but having trouble passing the scale parameter to the loss function, getting some weird tensorflow error, needs more debugging* Without the determinant in the loss function, it looks like loss goes down, so maybe on the right track? * It's actually weird that ... | from scipy.stats import norm
for i in range(-10, 10):
eps = i / 1000
l = norm.cdf(0 - eps)
r = norm.cdf(0 + eps)
print(eps, '\t', l - r)
a = np.array([[[-1, -2], [-3, -4]], [[1,2], [3, 4]], [[5,6], [7, 8]]])
b = np.array([100, 200]).reshape([1, 1, 2])
c = a + b
c[:, :, :] | _____no_output_____ | MIT | realnvp/Simple Gaussian Test.ipynb | bjlkeng/sandbox |
Problem H: Gold MiningReply the maximum sum of gold mines, that can be mined with single well. Input- Number of test case + N: Number of gold layer + N lines (x1, x2, y) start, stop and depth of the gold layer Outputfor each test case- 1/3 of total length of gold layer that can be mined with single well (2 d... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
MCPC 2018 Problem-H: Gold Mining
'''
import sys
def check_mines(mines, p1, p2):
'''
mines: list of tuple (x1, x2, y)
p1, p2: tuple (x,y)
return: total length of mines on the p1-p2 line
'''
total_len = 0
slope_p1_p2 = (p2[0]-p1[0]) / (p2[1]-... | _____no_output_____ | MIT | How_to_solve_Problem_H.ipynb | ShinjiKatoA16/mcpc2018ucsy |
Calculating a custom statistic This example shows how to define and use a custom `iris.analysis.Aggregator`, that provides a new statistical operator foruse with cube aggregation functions such as `~iris.cube.Cube.collapsed`, `~iris.cube.Cube.aggregated_by` or `~iris.cube.Cube.rolling_window`.In this case, we have a 2... | import numpy as np
from iris.util import rolling_window
def count_spells(data, threshold, axis, spell_length):
"""
Function to calculate the number of points in a sequence where the value
has exceeded a threshold value for at least a certain number of timepoints.
Generalised to operate on multiple time... | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
Load the whole time-sequence as a single cube. | import iris
file_path = iris.sample_data_path('E1_north_america.nc')
cube = iris.load_cube(file_path)
cube | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
Make an aggregator from the user function. | from iris.analysis import Aggregator
SPELL_COUNT = Aggregator('spell_count',
count_spells,
units_func=lambda units: 1) | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
Define the parameters of the test. | threshold_temperature = 280.0
spell_years = 5 | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
Calculate the statistic. | warm_periods = cube.collapsed('time', SPELL_COUNT,
threshold=threshold_temperature,
spell_length=spell_years)
warm_periods.rename('Number of 5-year warm spells in 240 years')
warm_periods | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
Plot the results. | %matplotlib inline
import iris.quickplot as qplt
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['figure.figsize'] = [12, 8]
qplt.contourf(warm_periods, cmap='RdYlBu_r')
plt.gca().coastlines(); | _____no_output_____ | Apache-2.0 | examples/iris/custom-statistic.ipynb | RETURN-project/eucp |
plot windparks: either all with opacity or aggregate to windparks and maybe use size as capacity indicator? | fig, ax = plt.subplots(figsize = (9,7))
ax.set_xlim(-180,-65)
ax.set_ylim(20,75)
shpUSA.plot(color=COLORS[4],ax=ax)
plt.plot(wpUSA.xlong,wpUSA.ylat,'o',alpha=0.1,markersize=2)
import xarray as xr
from matplotlib.patches import Rectangle
NZera5 = xr.open_dataset(era_path + '/NZ/era5_wind_NZ_198701.nc')
NZmerra2 = xr.ope... | _____no_output_____ | MIT | plot_maps.ipynb | KatharinaGruber/windpower_GWA |
Test CoffeaThis will test Coffea to see if we can figure out how to use it with our code.First are the includes from coffea. This is based on the [example written by Ben](https://github.com/CoffeaTeam/coffea/blob/master/binder/servicex/ATLAS/LocalExample.ipynb). | from servicex import ServiceXDataset
from coffea.processor.servicex import DataSource, Analysis
from coffea.processor.servicex import LocalExecutor
import matplotlib.pyplot as plt
from coffea import hist, processor
from IPython.display import display, update_display, HTML | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
And imports connected with running servicex. | from func_adl import ObjectStream
from func_adl_servicex import ServiceXSourceUpROOT
from hist import Hist
import mplhep as mpl
import awkward as ak
from utils import files | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
Methods copied to help us get all leptons from the source files | def apply_event_cuts (source: ObjectStream) -> ObjectStream:
'''Event level cuts for the analysis. Keep from sending data that we aren't going to need at all in the end.
'''
return (source
.Where(lambda e: e.trigE or e.trigM))
def good_leptons(source: ObjectStream) -> ObjectStream:
'''Sele... | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
Create the `func_adl` cuts to get the data. The dataset we use here doesn't matter, as long as it "looks" like all the datasets we are going to be processing. | ds = ServiceXSourceUpROOT('cernopendata://dummy', files['ggH125_ZZ4lep']['treename'], backend_name='open_uproot')
ds.return_qastle = True
leptons = good_leptons(apply_event_cuts(ds)) | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
The analysis code that will apply the 4 lepton cuts and make the 4 lepton mass plot. | class ATLAS_Higgs_4L(Analysis):
@staticmethod
def process(events):
import awkward as ak
from collections import defaultdict
sumw = defaultdict(float)
mass_hist = hist.Hist(
"Events",
hist.Cat("dataset", "Dataset"),
hist.Bin("mass", "... | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
Create the data source that we will be running against. | def make_ds(name: str, query: ObjectStream):
'''Create a ServiceX Datasource for a particular ATLAS Open data file
'''
datasets = [ServiceXDataset(files[name]['files'], backend_name='open_uproot')]
return DataSource(query=query, metadata={'dataset': name}, datasets=datasets) | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
And run! | analysis = ATLAS_Higgs_4L()
# TODO: It would be good if datatype was determined automagically (there is enough info)
executor = LocalExecutor()
#executor = DaskExecutor(client_addr="tls://localhost:8786")
datasource = make_ds('ggH125_ZZ4lep', leptons)
async def run_updates_stream(accumulator_stream):
global first
... | _____no_output_____ | MIT | notebooks/atlas-demo-coffea.ipynb | oshadura/opendata-higgs-discovery |
dwtls: Discrete Wavelet Transform LayerSThis library provides downsampling (DS) layers using discrete wavelet transforms (DWTs), which we call DWT layers.Conventional DS layers lack either antialiasing filters and the perfect reconstruction property, so downsampled features are aliased and entire information of input ... | !pip install dwtls
import torch
import dwtls.dwt_layers | _____no_output_____ | MIT | examples/tutorial.ipynb | TomohikoNakamura/dwtls |
DWT layers with fixed waveletsThe DWT layer (including its extensions) is implemeted as a subclass of `torch.nn.Module` provided by PyTorch, so we can easily use it in PyTorch-based scripts. Also, this layer is differentiable. | dwt_layer = dwtls.dwt_layers.DWT(wavelet="haar")
feature = torch.normal(0.0, 1.0, size=(1,1,20)).float()
output_feature = dwt_layer(feature)
print('Input:', feature)
print("Output:", output_feature) | _____no_output_____ | MIT | examples/tutorial.ipynb | TomohikoNakamura/dwtls |
TDWT layerThe TDWT layer has trainable wavelets (precisely, predict and update filters of lifting scheme).For example, we can define the TDWT layer having a pair of the prediction and update filters initialized with Haar wavelet. | tdwt_layer = dwtls.dwt_layers.MultiStageLWT([
dict(predict_ksize=3, update_ksize=3,
requires_grad={"predict": True, "update": True},
initial_values={"predict": [0,1,0], "update": [0,0.5,0]})
]) | _____no_output_____ | MIT | examples/tutorial.ipynb | TomohikoNakamura/dwtls |
The `tdwt_layer._predict_weight` and `tdwt_layer._update_weight` of this layer are trainable jointly with other DNN components. We show three structures of the trainable DWT layers used in our music source separation paper [1]. [1] Tomohiko Nakamura, Shihori Kozuka, and Hiroshi Saruwatari, “Time-Domain Audio Source Se... | # Type A
tdwt_layer = dwtls.dwt_layers.MultiStageLWT([
dict(predict_ksize=3, update_ksize=3,
requires_grad={"predict": True, "update": True},
initial_values={"predict": [0,1,0], "update": [0,0.5,0]})
])
# Type B
tdwt_layer = dwtls.dwt_layers.MultiStageLWT([
dict(predict_ksize=1, update_ksize... | _____no_output_____ | MIT | examples/tutorial.ipynb | TomohikoNakamura/dwtls |
WN-TDWT layerThe TDWT layer can be incorporated into many types of DNNs, but such straightforward extension does not guarantee that it has anti-aliasing filters, while it has the perfect reconstruction property owing to the lifting scheme.The WN-TDWT layer is developed to overcome this problem. It has both properties ... | # Type A
tdwt_layer = dwtls.dwt_layers.WeightNormalizedMultiStageLWT([
dict(predict_ksize=3, update_ksize=3,
requires_grad={"predict": True, "update": True},
initial_values={"predict": [0,1,0], "update": [0,0.5,0]})
]) | _____no_output_____ | MIT | examples/tutorial.ipynb | TomohikoNakamura/dwtls |
Directed graphical modelsWe illustrate some basic properties of DGMs. | !pip install causalgraphicalmodels
!pip install pgmpy
from causalgraphicalmodels import CausalGraphicalModel
import pgmpy
import numpy as np
import pandas as pd | _____no_output_____ | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Make the model | sprinkler = CausalGraphicalModel(
nodes=["cloudy", "rain", "sprinkler", "wet", "slippery"],
edges=[
("cloudy", "rain"),
("cloudy", "sprinkler"),
("rain", "wet"),
("sprinkler", "wet"),
("wet", "slippery")
]
)
| _____no_output_____ | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Draw the model | # draw return a graphviz `dot` object, which jupyter can render
out = sprinkler.draw()
type(out)
display(out)
out.render() | _____no_output_____ | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Display the factorization | print(sprinkler.get_distribution()) | P(season)P(sprinkler|season)P(rain|season)P(wet|rain,sprinkler)P(slippery|wet)
| MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
D-separation |
# check for d-seperation of two nodes
sprinkler.is_d_separated("slippery", "cloudy", {"wet"}) | _____no_output_____ | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Extract CI relationships | # get all the conditional independence relationships implied by a CGM
CI = sprinkler.get_all_independence_relationships()
print(CI)
records = []
for ci in CI:
record = (ci[0], ci[1], ', '.join(x for x in ci[2]))
records.append(record)
print(records)
df = pd.DataFrame(records, columns = ('X', 'Y', 'Z'))
display(df)... | \begin{tabular}{lll}
\toprule
X & Y & Z \\
\midrule
rain & sprinkler & cloudy \\
rain & slippery & wet \\
rain & slippery & sprinkler, wet \\
rain & slippery & cloudy, wet \\
... | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Inference |
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
# Defining the model structure. We can define the network by just passing a list of edges.
model = BayesianModel([('C', 'S'), ('C', 'R'), ('S', 'W'), ('R', 'W'), ('W', 'L')])
# Defining individual CPDs.
cpd_c = TabularCPD(variable=... | Finding Elimination Order: : 100%|██████████| 4/4 [00:00<00:00, 557.40it/s]
Eliminating: W: 100%|██████████| 4/4 [00:00<00:00, 341.96it/s]
Finding Elimination Order: : 100%|██████████| 3/3 [00:00<00:00, 710.42it/s]
Eliminating: C: 100%|██████████| 3/3 [00:00<00:00, 435.59it/s]
Finding Elimination Order: : 100%|████████... | MIT | notebooks/sprinkler_pgm.ipynb | animesh-007/pyprobml |
Method4 DCT based DOST + Huffman encoding Import Libraries | import mne
import numpy as np
from scipy.fft import fft,fftshift
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
from scipy.signal import freqz
from scipy import signal
from scipy.fftpack import fft, dct, idct
from itertools import islice
import pandas as pd
import os | _____no_output_____ | Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
Preprocessing Data loading | acc = pd.read_csv('ACC.csv')
acc = acc.iloc[1:]
acc.columns = ['column1','column2','column3']
np.savetxt('acc.txt',acc)
acc_c1 = acc["column1"]
acc_c2 = acc["column2"]
acc_c3 = acc["column3"]
acc_array_c1 = acc_c1.to_numpy() #save the data into an ndarray
acc_array_c2 = acc_c2.to_numpy()
acc_array_c3 = acc_c3.to_num... | _____no_output_____ | Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
Butterworth Filter to denoising | def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y =... | _____no_output_____ | Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
Transformation --- DCT based DOST | from scipy.fftpack import fft, dct
aN1 = dct(rounded_signal1, type = 2, norm = 'ortho')
aN2 = dct(rounded_signal2, type = 2, norm = 'ortho')
aN3 = dct(rounded_signal3, type = 2, norm = 'ortho')
def return_N(target):
if target > 1:
for i in range(1, int(target)):
if (2 ** i >= target):
... | _____no_output_____ | Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
Huffman Coding INSTRUCTION ON HOW TO COMPRESS THE DATA BY HUFFMAN CODING(I used the package "tcmpr 0.2" and "pyhuff 1.1". These two packages provided the same compression result. So here, we just use "tcmpr 0.2")1. Open your termial or git bash, enter "pip install tcmpr" to install the "tcmpr 0.2" package2. Enter the... | # Do Huffman encoding based on the instruction above
# or run this trunk if this scratch locates in the same directory with the signal you want to encode
os.system('tcmpr int_cN1.txt')
os.system('tcmpr int_cN2.txt')
os.system('tcmpr int_cN3.txt') | _____no_output_____ | Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
Reconstruction | os.system('tcmpr -d int_cN1.txt.huffman')
os.system('tcmpr -d int_cN2.txt.huffman')
os.system('tcmpr -d int_cN3.txt.huffman')
decoded_data1 = np.loadtxt(fname = "int_cN1.txt")
decoded_data2 = np.loadtxt(fname = "int_cN2.txt")
decoded_data3 = np.loadtxt(fname = "int_cN3.txt")
recover_signal1 = decoded_data1
recover_sign... | The PRD is 3.16%
| Apache-2.0 | DOST_Huffman/DCT_DOST_Huffman_ACC.ipynb | BaiyingLu/Data-Compression-Toolbox |
ElasticNet with RobustScaler **This Code template is for the regression analysis using a ElasticNet Regression and the feature rescaling technique RobustScaler in a pipeline** Required Packages | import warnings as wr
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.model_selection import train_test_split
from sk... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path) #reading file
df.head()#displaying initial entries
print('Number of rows are :',df.shape[0], ',and number of columns are :',df.shape[1])
df.columns.tolist()
| _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_du... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | plt.figure(figsize = (15, 10))
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype = bool))
sns.heatmap(corr, mask = mask, linewidths = 1, annot = True, fmt = ".2f")
plt.show()
correlation = df[df.columns[1:]].corr()[target][:]
correlation | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | #spliting data into X(features) and Y(Target)
X=df[features]
Y=df[target] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | #we can choose randomstate and test_size as over requerment
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 1) #performing datasplitting | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Model
Data Scaling
**Used RobustScaler**
* It scales features using statistics that are robust to outliers.
* This method removes the median and scales the data in the range between 1st quartile and 3rd quartile. i.e., in between 25th quantile and 75th quantile range. This range is also called an Interquartile ra... | #training the ElasticNet
Input=[("scaler",RobustScaler()),("model",ElasticNet(random_state = 5))]
model = Pipeline(Input)
model.fit(X_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Model Accuracyscore() method return the mean accuracy on the given test data and labels.In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. | print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100))
#prediction on testing set
prediction=model.predict(X_test) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Model evolution**r2_score:** The r2_score function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions.**MAE:** The mean abosolute error function calculates the amount of total error(absolute average distance between the real data and the predicted data)... | print('Mean Absolute Error:', mean_absolute_error(y_test, prediction))
print('Mean Squared Error:', mean_squared_error(y_test, prediction))
print('Root Mean Squared Error:', np.sqrt(mean_squared_error(y_test, prediction)))
print("R-squared score : ",r2_score(y_test,prediction))
#ploting actual and predicted
red =... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Prediction Plot¶First, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(10,6))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(X_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler.ipynb | surya2365/ds-seed |
Let's Import Our Libraries | # Keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Flatten, LSTM, Conv1D, MaxPooling1D, Dropout, Activation
from keras.layers.embeddings import Embedding
# Plot
import plotly.offline as py
imp... | Using TensorFlow backend.
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's start by exploring the data. | df = pd.read_csv("socialmedia-disaster-tweets-DFE.csv", encoding='latin-1')
df.shape
df.head(5)
df.columns | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
The 'tweet' column has tweets and 'choose_one' has the classification. Let's determine the number of unique classifications. | df.choose_one.unique() | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's work on cleaning up the data | df = df[["text", "choose_one"]]
df["choose_one"] = df.choose_one.replace({"Relevant": 1, "Not Relevant": 0})
df.rename(columns={"choose_one":"label"}, inplace=True)
df.label=pd.to_numeric(df.label, errors='coerce')
df.dropna(inplace=True) | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's check and see how the data looks. | df.label.unique()
df.head(5)
df["text"] = df["text"].str.replace(r"http\S+|http|@\S+|at", "")
df["text"] = df["text"].str.replace(r"[^A-Za-z0-9(),!?@\'\`\"\_\n]", " ")
df["text"] = df["text"].str.lower()
df.head(5)
df.columns | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's Tokenzie: We'll Turn our Sentences into Lists of Words | from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
df["tokens"] = df["text"].apply(tokenizer.tokenize) | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Tokens will give us more insight into the data | all_words = [word for tokens in df["tokens"] for word in tokens]
sentence_lengths = [len(tokens) for tokens in df["tokens"]]
vocabulary = sorted(set(all_words))
print("%s words total, with a vocabulary size of %s." % (len(all_words), len(vocabulary)))
print("Max sentence length is %s." % max(sentence_lengths)) | Max sentence length is 34.
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's Embed: Turning Words into Numbers | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
TFIDF Tokenizer for Our Classical ML Models | text = df["text"].tolist()
labels = df["label"].tolist()
X_train, X_test, y_train, y_test = train_test_split(text, labels, test_size=0.2,random_state=40)
tfidf_vectorizer = TfidfVectorizer()
X_train_tfidf = tfidf_vectorizer.fit_transform(X_train)
X_test_tfidf = tfidf_vectorizer.transform(X_test)
X_test_tfidf.shape | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
NN Specific Tokenizer | vocabulary_size = 40000
tokenizer = Tokenizer(num_words = vocabulary_size)
tokenizer.fit_on_texts(df['text'])
sequences = tokenizer.texts_to_sequences(X_train)
X_train_nn = pad_sequences(sequences, maxlen=28)
sequences = tokenizer.texts_to_sequences(X_test)
X_test_nn = pad_sequences(sequences, maxlen=28)
X_train_nn ... | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Here We'll Define a New Classifier | class NbSvmClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, C=1.0, dual=False, n_jobs=1):
self.C = C
self.dual = dual
self.n_jobs = n_jobs
def predict(self, x):
# Verify that model has been fit
check_is_fitted(self, ['_r', '_clf'])
return self._clf.... | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's get a baseline using Logisitc Regression | classifier = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg', multi_class='multinomial', n_jobs=-1, random_state=40)
classifier.fit(X_train_tfidf, y_train)
y_predicted_tfidf = classifier.predict(X_test_tfidf)
precision = precision_score(y_test, y_predicted_tfidf, pos_label=None,average='weighted... | 0.7745952843343159
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Now We'll Utilize Our NBSVM Classifier | classifier = NbSvmClassifier(C=4, dual=True, n_jobs=-1).fit(X_train_tfidf, y_train)
classifier.fit(X_train_tfidf, y_train)
y_predicted_tfidf = classifier.predict(X_test_tfidf)
precision = precision_score(y_test, y_predicted_tfidf, pos_label=None,average='weighted')
print(precision) | 0.8057456468641322
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Now Let's Apply Grid Search to the Model | from sklearn.model_selection import GridSearchCV
param_grid = {
'C': [3.0, 3.2, 3.25, 3.3, 3.4, 3.5],
'dual' : [True, False]
}
%%time
gs_classifier = GridSearchCV(NbSvmClassifier(), param_grid, n_jobs=-1)
gs_classifier = gs_classifier.fit(X_train_tfidf, y_train)
gs_classifier.best_score_
gs_classifier.best_para... | _____no_output_____ | MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
We don't seem to be getting much extra juice from applying grid search to this model. Let's Try Regular SVM | classifier = SGDClassifier().fit(X_train_tfidf, y_train)
classifier.fit(X_train_tfidf, y_train)
y_predicted_tfidf = classifier.predict(X_test_tfidf)
precision = precision_score(y_test, y_predicted_tfidf, pos_label=None,average='weighted')
print(precision) | 0.7946891903618641
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Let's Try Multinomial Naive Bayes | classifier = SGDClassifier().fit(X_train_tfidf, y_train)
classifier.fit(X_train_tfidf, y_train)
y_predicted_tfidf = classifier.predict(X_test_tfidf)
precision = precision_score(y_test, y_predicted_tfidf, pos_label=None,average='weighted')
print(precision) | 0.7960386107807245
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
The last three approaches yielded pretty similar results. Let's try a deep learning model. Build the network with LSTM Network ArchitectureOur network is going to start with an embedding layer. This layer lets the system expand each token into a much larger vector space. By doing so we can represent each word in a mo... | def create_lstm():
model = Sequential()
model.add(Embedding(40000, 100, input_length=28))
model.add(LSTM(100, dropout=0.9, recurrent_dropout=0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
classifier =... | 0.8128093975364307
| MIT | disaster_tweets.ipynb | Hack-My-Life/disaster_tweets |
Convolutional Neural Networks---In this notebook, we train a **CNN** to classify images from the CIFAR-10 database.The images in this database are small color images that fall into one of ten classes; some example images are pictured below. Test for [CUDA](http://pytorch.org/docs/stable/cuda.html)Since these are lar... | import torch
import numpy as np
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...') | CUDA is available! Training on GPU ...
| MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb | sroy8091/deep-learning-v2-pytorch |
--- Load the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)Downloading may take a minute. We load in the training and test data, split the training data into a training and validation set, then create DataLoaders for each of these sets of data. | from torchvision import datasets
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 20
# percentage of training set to use as validation
valid_size = 0.2
... | Files already downloaded and verified
Files already downloaded and verified
| MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb | sroy8091/deep-learning-v2-pytorch |
Visualize a Batch of Training Data | import matplotlib.pyplot as plt
%matplotlib inline
# helper function to un-normalize and display an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
plt.imshow(np.transpose(img, (1, 2, 0))) # convert from Tensor image
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels ... | _____no_output_____ | MIT | convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb | sroy8091/deep-learning-v2-pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.