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 |
|---|---|---|---|---|---|
Set your number of training epochs and train your GAN! | # set number of epochs
n_epochs = 100 ## Best is 50 epochs and lr = .0002
print(train_on_gpu)
# call training function
losses = train(D, G, n_epochs=n_epochs)
##Saving the Generator and the Discrminator
def save_generator(model):
model_name = 'trained_generator.pt'
checkpoint = {'z_size' : model.z_size,
... | _____no_output_____ | MIT | GAN_face_generation.ipynb | kaustav1987/Human-Face-Generation-using-GAN |
Training lossPlot the training losses for the generator and discriminator, recorded after each epoch. | fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator', alpha=0.5)
plt.plot(losses.T[1], label='Generator', alpha=0.5)
plt.title("Training Losses")
plt.legend() | _____no_output_____ | MIT | GAN_face_generation.ipynb | kaustav1987/Human-Face-Generation-using-GAN |
Generator samples from trainingView samples of images from the generator, and answer a question about the strengths and weaknesses of your trained models. | # helper function for viewing a list of passed in sample images
def view_samples(epoch, samples):
fig, axes = plt.subplots(figsize=(16,4), nrows=2, ncols=8, sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
img = img.detach().cpu().numpy()
img = np.transpose(img, (1, ... | _____no_output_____ | MIT | GAN_face_generation.ipynb | kaustav1987/Human-Face-Generation-using-GAN |
Transforms> Definition of `Transform` and `Pipeline` The classes here provide functionality for creating a composition of *partially reversible functions*. By "partially reversible" we mean that a transform can be `decode`d, creating a form suitable for display. This is not necessarily identical to the original form (... | #exports
def type_hints(f):
"Same as `typing.get_type_hints` but returns `{}` if not allowed type"
return typing.get_type_hints(f) if isinstance(f, typing._allowed_types) else {}
#export
def anno_ret(func):
"Get the return annotation of `func`"
if not func: return None
ann = type_hints(func)
if ... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Types `TensorImage`, `TensorImageBW` and `TensorMask` are subclasses of `torch.Tensor` that know how to show themselves. | #export
@delegates(plt.subplots, keep=True)
def subplots(nrows=1, ncols=1, **kwargs):
fig,ax = plt.subplots(nrows,ncols,**kwargs)
if nrows*ncols==1: ax = array([ax])
return fig,ax
#export
class TensorImageBase(TensorBase):
_show_args = {'cmap':'viridis'}
def show(self, ctx=None, **kwargs):
r... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
TypeDispatch - The following class is the basis that allows us to do type dipatch with type annotations. It contains a dictionary type -> functions and ensures that the proper function is called when passed an object (depending on its type). | #export
class TypeDispatch:
"Dictionary-like object; `__getitem__` matches keys of types using `issubclass`"
def __init__(self, *funcs):
self.funcs,self.cache = {},{}
for f in funcs: self.add(f)
self.inst = None
def _reset(self):
self.funcs = {k:self.funcs[k] for k in sorted... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Transform - | #export
_tfm_methods = 'encodes','decodes','setups'
class _TfmDict(dict):
def __setitem__(self,k,v):
if k not in _tfm_methods or not callable(v): return super().__setitem__(k,v)
if k not in self: super().__setitem__(k,TypeDispatch())
res = self[k]
res.add(v)
#export
class _TfmMeta(t... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
A `Transform` is the main building block of the fastai data pipelines. In the most general terms a transform can be any function you want to apply to your data, however the `Transform` class provides several mechanisms that make the process of building them easy and flexible. The main `Transform` features:- **Type disp... | class A(Transform): pass
@A
def encodes(self, x): return x+1
f1 = A()
test_eq(f1(1), 2)
class B(A): pass
f2 = B()
test_eq(f2(1), 2)
class A(Transform): pass
f3 = A()
test_eq_type(f3(2), 2)
test_eq_type(f3.decode(2.0), 2.0) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
`Transform` can be used as a decorator, to turn a function into a `Transform`. | f = Transform(lambda o:o//2)
test_eq_type(f(2), 1)
test_eq_type(f.decode(2.0), 2.0)
@Transform
def f(x): return x//2
test_eq_type(f(2), 1)
test_eq_type(f.decode(2.0), 2.0) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
You can derive from `Transform` and use `encodes` for your encoding function. | class A(Transform):
def encodes(self, x:TensorImage): return -x
def decodes(self, x:TensorImage): return x+1
def setups (self, x:TensorImage): x.foo = 'a'
f = A()
t = f(im_t)
test_eq(t, -im_t)
test_eq(f(1), 1)
test_eq(type(t), TensorImage)
test_eq(f.decode(t), -im_t+1)
test_eq(f.decode(1), 1)
f.setup(im_t)
... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Without return annotation we get an `Int` back since that's what was passed. | class A(Transform): pass
@A
def encodes(self, x:Int): return x//2
@A
def encodes(self, x:float): return x+1
f = A()
test_eq_type(f(Int(2)), Int(1))
test_eq_type(f(2), 2)
test_eq_type(f(2.), 3.) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Without return annotation we don't cast if we're not a subclass of the input type. | class A(Transform):
def encodes(self, x:Int): return x/2
def encodes(self, x:float): return x+1
f = A()
test_eq_type(f(Int(2)), 1.)
test_eq_type(f(2), 2)
test_eq_type(f(Float(2.)), Float(3.)) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
With return annotation `None` we get back whatever Python creates usually. | def func(x)->None: return x/2
f = Transform(func)
test_eq_type(f(2), 1.)
test_eq_type(f(2.), 1.) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Since `decodes` has no return annotation, but `encodes` created an `Int` and we pass that result here to `decode`, we end up with an `Int`. | def func(x): return Int(x+1)
def dec (x): return x-1
f = Transform(func,dec)
t = f(1)
test_eq_type(t, Int(2))
test_eq_type(f.decode(t), Int(1)) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
If the transform has `filt` then it's only applied if `filt` param matches. | f.filt = 1
test_eq(f(1, filt=1),2)
test_eq_type(f(1, filt=0), 1) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
If `as_item=True` the transform takes tuples as a whole and is applied to them. | class A(Transform):
def encodes(self, xy): x,y=xy; return (x+y,y)
def decodes(self, xy): x,y=xy; return (x-y,y)
f = A(as_item=True)
t = f((1,2))
test_eq(t, (3,2))
test_eq(f.decode(t), (1,2))
f.filt = 1
test_eq(f((1,2), filt=1), (3,2))
test_eq(f((1,2), filt=0), (1,2))
class AL(Transform): pass
@AL
def encodes(... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
If `as_item=False` the transform is applied to each element of a listy input. | def neg_int(x:numbers.Integral): return -x
f = Transform(neg_int, as_item=False)
test_eq(f([1]), (-1,))
test_eq(f([1.]), (1.,))
test_eq(f([1.,2,3.]), (1.,-2,3.))
test_eq(f.decode([1,2]), (1,2))
#export
class InplaceTransform(Transform):
"A `Transform` that modifies in-place and just returns whatever it's passed"
... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
TupleTransform | #export
class TupleTransform(Transform):
"`Transform` that always treats `as_item` as `False`"
as_item_force=False
#export
class ItemTransform (Transform):
"`Transform` that always treats `as_item` as `True`"
as_item_force=True
def float_to_int(x:(float,int)): return Int(x)
f = TupleTransform(float_to_... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Non-type-constrained functions are applied to all elements of a tuple. | class A(TupleTransform): pass
@A
def encodes(self, x): return x+1
@A
def decodes(self, x): return x-1
f = A()
t = f((1,2.0))
test_eq_type(t, (2,3.0))
test_eq_type(f.decode(t), (1,2.0)) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Type-constrained functions are applied to only matching elements of a tuple, and return annotations are only applied where matching. | class B(TupleTransform):
def encodes(self, x:int): return Int(x+1)
def encodes(self, x:str): return x+'1'
def decodes(self, x:Int): return x//2
f = B()
start = (1.,2,'3')
t = f(start)
test_eq_type(t, (1.,Int(3),'31'))
test_eq(f.decode(t), (1.,Int(1),'31')) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
The same behavior also works with `typing` module type classes. | class A(Transform): pass
@A
def encodes(self, x:numbers.Integral): return x+1
@A
def encodes(self, x:float): return x*3
@A
def decodes(self, x:int): return x-1
f = A()
start = 1.0
t = f(start)
test_eq(t, 3.)
test_eq(f.decode(t), 3)
f = A(as_item=False)
start = (1.,2,3.)
t = f(start)
test_eq(t, (3.,3,9.))
test_eq(f.de... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Transform accepts lists | def a(x): return L(x_+1 for x_ in x)
def b(x): return L(x_-1 for x_ in x)
f = TupleTransform(a,b)
t = f((L(1,2),))
test_eq(t, (L(2,3),))
test_eq(f.decode(t), (L(1,2),)) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Func - | #export
def get_func(t, name, *args, **kwargs):
"Get the `t.name` (potentially partial-ized with `args` and `kwargs`) or `noop` if not defined"
f = getattr(t, name, noop)
return f if not (args or kwargs) else partial(f, *args, **kwargs) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
This works for any kind of `t` supporting `getattr`, so a class or a module. | test_eq(get_func(operator, 'neg', 2)(), -2)
test_eq(get_func(operator.neg, '__call__')(2), -2)
test_eq(get_func(list, 'foobar')([2]), [2])
t = get_func(torch, 'zeros', dtype=torch.int64)(5)
test_eq(t.dtype, torch.int64)
a = [2,1]
get_func(list, 'sort')(a)
test_eq(a, [1,2]) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Transforms are built with multiple-dispatch: a given function can have several methods depending on the type of the object received. This is done directly with the `TypeDispatch` module and type-annotation in `Transform`, but you can also use the following class. | #export
class Func():
"Basic wrapper around a `name` with `args` and `kwargs` to call on a given type"
def __init__(self, name, *args, **kwargs): self.name,self.args,self.kwargs = name,args,kwargs
def __repr__(self): return f'sig: {self.name}({self.args}, {self.kwargs})'
def _get(self, t): return get_fu... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
You can call the `Func` object on any module name or type, even a list of types. It will return the corresponding function (with a default to `noop` if nothing is found) or list of functions. | test_eq(Func('sqrt')(math), math.sqrt)
test_eq(Func('sqrt')(torch), torch.sqrt)
@patch
def powx(x:math, a): return math.pow(x,a)
@patch
def powx(x:torch, a): return torch.pow(x,a)
tst = Func('powx',a=2)([math, torch])
test_eq([f.func for f in tst], [math.powx, torch.powx])
for t in tst: test_eq(t.keywords, {'a': 2})
#... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
`Sig` is just sugar-syntax to create a `Func` object more easily with the syntax `Sig.name(*args, **kwargs)`. | f = Sig.sqrt()
test_eq(f(math), math.sqrt)
test_eq(f(torch), torch.sqrt) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Pipeline - | #export
def compose_tfms(x, tfms, is_enc=True, reverse=False, **kwargs):
"Apply all `func_nm` attribute of `tfms` on `x`, maybe in `reverse` order"
if reverse: tfms = reversed(tfms)
for f in tfms:
if not is_enc: f = f.decode
x = f(x, **kwargs)
return x
def to_int (x): return Int(x)
de... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
`Pipeline` is a wrapper for `compose_tfm`. You can pass instances of `Transform` or regular functions in `funcs`, the `Pipeline` will wrap them all in `Transform` (and instantiate them if needed) during the initialization. It handles the transform `setup` by adding them one at a time and calling setup on each, goes thr... | # Empty pipeline is noop
pipe = Pipeline()
test_eq(pipe(1), 1)
pipe.set_as_item(False)
test_eq(pipe((1,)), (1,))
# Check pickle works
assert pickle.loads(pickle.dumps(pipe))
class IntFloatTfm(Transform):
def encodes(self, x): return Int(x)
def decodes(self, x): return Float(x)
foo=1
int_tfm=IntFloatTfm()... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Transforms are available as attributes named with the snake_case version of the names of their types. Attributes in transforms can be directly accessed as attributes of the pipeline. | test_eq(pipe.int_float_tfm, int_tfm)
test_eq(pipe.foo, 1)
pipe = Pipeline([int_tfm, int_tfm])
pipe.int_float_tfm
test_eq(pipe.int_float_tfm[0], int_tfm)
test_eq(pipe.foo, [1,1])
# Check opposite order
pipe = Pipeline([int_tfm,neg_tfm])
t = pipe(start)
test_eq(t, -2)
test_stdout(lambda:pipe.show(t), '-2')
class A(Trans... | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Methods | #TODO: method examples
show_doc(Pipeline.__call__)
show_doc(Pipeline.decode)
show_doc(Pipeline.decode_batch)
pipe.set_as_item(False)
t = tensor([1,2,3])
pipe.filt=1
test_eq(pipe.decode_batch([t,t+1], max_n=2), [(0,-1),(-1,-2)])
show_doc(Pipeline.setup) | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
During the setup, the `Pipeline` starts with no transform and adds them one at a time, so that during its setup, each transform gets the items processed up to its point and not after. | #hide
#Test is with TfmdList | _____no_output_____ | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Export - | #hide
from local.notebook.export import notebook2script
notebook2script(all_fs=True) | Converted 00_test.ipynb.
Converted 01_core.ipynb.
Converted 01a_torch_core.ipynb.
Converted 02_script.ipynb.
Converted 03_dataloader.ipynb.
Converted 04_transform.ipynb.
Converted 05_data_core.ipynb.
Converted 06_data_transforms.ipynb.
Converted 07_vision_core.ipynb.
Converted 08_pets_tutorial.ipynb.
Converted 09_visio... | Apache-2.0 | dev/04_transform.ipynb | dejanbatanjac/fastai_dev |
Personal Beacon AnalysisThis notebook is dedicated to exploring the data captured at my own apartment using Beacon 7 | import pandas as pd
import numpy as np
import os
from datetime import datetime | _____no_output_____ | MIT | notebooks/archive/0.2.0-hef-beacon-personal-analysis.ipynb | intelligent-environments-lab/utx000 |
Data Import | b7 = pd.DataFrame()
for file in os.listdir('/Users/hagenfritz/Projects/utx000/data/raw/bpeace2/beacon/B07/sensirion/'):
temp = pd.read_csv(f'/Users/hagenfritz/Projects/utx000/data/raw/bpeace2/beacon/B07/sensirion/{file}',
index_col=0,parse_dates=True,infer_datetime_format=True)
b7 = pd.con... | _____no_output_____ | MIT | notebooks/archive/0.2.0-hef-beacon-personal-analysis.ipynb | intelligent-environments-lab/utx000 |
Visualizing | import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize=(16,8))
#b7_short = b7[datetime(2020,6,10):datetime(2020,6,11)]
ax.plot(b7.index,b7['CO2'])
ax.plot(b7.index,b7['PM_C_2p5']*10)
plt.show()
plt.close() | _____no_output_____ | MIT | notebooks/archive/0.2.0-hef-beacon-personal-analysis.ipynb | intelligent-environments-lab/utx000 |
To find the pattern of each comedian and find the reason of the likable1. Most common words2. size of vocab3. Amt. of profanity used Most common words | #read dmt
import pandas as pd
data=pd.read_pickle('/content/drive/MyDrive/Colab Notebooks/NLP/dtm.pkl')
data= data.transpose()
data.head()
#find the top 30 words said by each comedian
top_dict={}
for c in data.columns:
top= data[c].sort_values(ascending=False).head(30)
top_dict[c]=list(zip(top.index, top.values))... | ali
like, im, know, just, dont, shit, thats, youre, gonna, ok, lot, wanna, gotta, oh
---
anthony
im, like, know, dont, joke, got, thats, said, anthony, day, say, just, guys, people
---
bill
like, just, right, im, know, dont, gonna, got, fucking, yeah, shit, youre, thats, dude
---
bo
know, like, think, im, love, bo, jus... | MIT | Exploratory_Data_Analysis.ipynb | ArpitaChatterjee/Comedian-transcript-Analysis |
**NOTE:** At this point, we could go on and create word clouds. However, by looking at these top words, you can see that some of them have very little meaning and could be added to a stop words list. | #look at most common top words and add to dtop word list
from collections import Counter
#pull out top 30 words
words=[]
for comedian in data.columns:
top = [word for (word, count) in top_dict[comedian]]
for t in top:
words.append(t)
words
#aggregate the list and identify the most common words
Counter(words).... | _____no_output_____ | MIT | Exploratory_Data_Analysis.ipynb | ArpitaChatterjee/Comedian-transcript-Analysis |
**Finding*** Ali Wong says the s-word a lot and talks about her asian. I guess that's funny to me.* A lot of people use the F-word. Let's dig into that later. **Number of words** | #find no of unique words each of em used
#identify the nonzero item in dtm, meaning that the word appaers atleast once
unique_list=[]
for comedian in data.columns:
uniques = data[comedian].to_numpy().nonzero()[0].size
unique_list.append(uniques)
#create a new dataframe that contains this unique word count
data_wo... | _____no_output_____ | MIT | Exploratory_Data_Analysis.ipynb | ArpitaChatterjee/Comedian-transcript-Analysis |
**Finding*** **Vocabulary** * Ricky Gervais (British comedy) and Bill Burr (podcast host) use a lot of words in their comedy * Louis C.K. (self-depricating comedy) and Anthony Jeselnik (dark humor) have a smaller vocabulary* **Talking Speed** * Joe Rogan (blue comedy) and Bill Burr (podcast host) talk fast * Bo... | Counter(words).most_common()
#isolate just thse bad words
data_bad_words = data.transpose()[['fucking', 'fuck', 'shit']]
data_profanity = pd.concat([data_bad_words.fucking+ data_bad_words.fuck, data_bad_words.shit], axis=1)
data_profanity.columns = ['f_words', 's_words']
data_profanity
#lets create a scatter plot of ou... | _____no_output_____ | MIT | Exploratory_Data_Analysis.ipynb | ArpitaChatterjee/Comedian-transcript-Analysis |
**Finding*** **Averaging 2 F-Bombs Per Minute!** - I don't like too much swearing, especially the f-word, which is probably why I've never heard of Bill Bur, Joe Rogan and Jim Jefferies.* **Clean Humor** - It looks like profanity might be a good predictor of the type of comedy I like. Besides Ali Wong, my two other fa... | _____no_output_____ | MIT | Exploratory_Data_Analysis.ipynb | ArpitaChatterjee/Comedian-transcript-Analysis | |
Hold_out Validation | #importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files |
Importing the data | data = pd.read_csv('data_cleaned.csv')
data.head()
data.isnull().sum() | _____no_output_____ | MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files |
Splitting Separating Dependent and Independent Variables | # For train set
data_x = data.drop(['Survived'], axis=1)
data_y = data['Survived'] | _____no_output_____ | MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files |
Creating Validation and test set | from sklearn.model_selection import train_test_split as tts
train1_x, test_x , train1_y, test_y = tts( data_x, data_y , test_size = 0.2 , random_state = 50, stratify = data_y) | _____no_output_____ | MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files |
train_x, val_x, train_y, val_y = tts(train1_x, train1_y, test_size = 0.2 , random_state = 51, stratify = train1_y)
print('training data ',train_x.shape,train_y.shape)
print('validation data ',val_x.shape,val_y.shape)
print('test data ',test_x.shape,test_y.shape) | training data (569, 24) (569,)
validation data (143, 24) (143,)
test data (179, 24) (179,)
| MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files | |
Checking Distribution of target class in train, test and validation set | train_y.value_counts()/len(train_y)
val_y.value_counts()/len(val_y)
test_y.value_counts()/len(test_y) | _____no_output_____ | MIT | 8 Selecting the Right Model/7. Implementing Hold-Out Validation/Hold-Out + Stratify.ipynb | IamVaibhavsar/Machine_Learning_Files |
Going deeper with TensorflowВ этом семинаре мы начнем изучать [Tensorflow](https://www.tensorflow.org/) для построения deep learning моделей.Для установки tf на свою машину* `pip install tensorflow` версия с поддержкой **cpu-only** для Linux & Mac OS* для автомагической поддержки GPU смотрите документацию [TF install ... | import tensorflow as tf
gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.1)
s = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options)) | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
ПриступимДля начала, давайте имплементируем простую функцию на numpy просто для сравнения. Напишите подсчет суммы квадратов чисел от 0 до N-1.**Подсказка:*** Массив чисел от 0 до N-1 включительно - numpy.arange(N) | import numpy as np
def sum_squares(N):
return <student.Implement_me()>
%%time
sum_squares(10**8) | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Tensoflow teaserDoing the very same thing | #I gonna be your function parameter
N = tf.placeholder('int64', name="input_to_your_function")
#i am a recipe on how to produce sum of squares of arange of N given N
result = tf.reduce_sum((tf.range(N)**2))
%%time
#example of computing the same as sum_squares
print(result.eval({N:10**8})) | 662921401752298880
CPU times: user 1.24 s, sys: 2.78 s, total: 4.02 s
Wall time: 3.19 s
| MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
How does it work?1. define placeholders where you'll send inputs;2. make symbolic graph: a recipe for mathematical transformation of those placeholders;3. compute outputs of your graph with particular values for each placeholder * output.eval({placeholder:value}) * s.run(output, {placeholder:value})* So far there a... | #Default placeholder that can be arbitrary float32 scalar, vertor, matrix, etc.
arbitrary_input = tf.placeholder('float32')
#Input vector of arbitrary length
input_vector = tf.placeholder('float32',shape=(None,))
#Input vector that _must_ have 10 elements and integer type
fixed_vector = tf.placeholder('int32',shape=(... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Visualizing graphsIt's often useful to visualize the computation graph when debugging or optimizing. Interactive visualization is where tensorflow really shines as compared to other frameworks. There's a special instrument for that, called Tensorboard. You can launch it from console:```tensorboard --logdir=/tmp/tboard... | # launch tensorflow the ugly way, uncomment if you need that
import os
port = 6000 + os.getuid()
print("Port: %d" % port)
#!killall tensorboard
os.system("tensorboard --logdir=./tboard --port=%d &" % port)
# show graph to tensorboard
writer = tf.summary.FileWriter("./tboard", graph=tf.get_default_graph())
writer.close... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
One basic functionality of tensorboard is drawing graphs. One you've run the cell above, go to `localhost:7007` in your browser and switch to _graphs_ tab in the topbar. Here's what you should see:Tensorboard also allows you to draw graphs (e.g. learning curves), record images & audio ~~and play flash games~~. This is ... | # Quest #1 - implement a function that computes a mean squared error of two input vectors
# Your function has to take 2 vectors and return a single number
<student.define_inputs_and_transformations()>
mse =<student.define_transformation()>
compute_mse = lambda vector1, vector2: <how to run you graph?>
# Tests
from s... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
variablesThe inputs and transformations have no value outside function call. This isn't too comfortable if you want your model to have parameters (e.g. network weights) that are always present, but can change their value over time.Tensorflow solves this with `tf.Variable` objects.* You can assign variable a value at a... | #creating shared variable
shared_vector_1 = tf.Variable(initial_value=np.ones(5))
#initialize variable(s) with initial values
s.run(tf.global_variables_initializer())
#evaluating shared variable (outside symbolicd graph)
print("initial value", s.run(shared_vector_1))
# within symbolic graph you use them just as any o... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
tf.gradients - why graphs matter* Tensorflow can compute derivatives and gradients automatically using the computation graph* Gradients are computed as a product of elementary derivatives via chain rule:$$ {\partial f(g(x)) \over \partial x} = {\partial f(g(x)) \over \partial g(x)}\cdot {\partial g(x) \over \partial x... | my_scalar = tf.placeholder('float32')
scalar_squared = my_scalar**2
#a derivative of scalar_squared by my_scalar
derivative = tf.gradients(scalar_squared, my_scalar)[0]
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-3,3)
x_squared, x_squared_der = s.run([scalar_squared,derivative],
... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Why that rocks | my_vector = tf.placeholder('float32',[None])
#Compute the gradient of the next weird function over my_scalar and my_vector
#warning! Trying to understand the meaning of that function may result in permanent brain damage
weird_psychotic_function = tf.reduce_mean((my_vector+my_scalar)**(1+tf.nn.moments(my_vector,[0])[1... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Almost done - optimizersWhile you can perform gradient descent by hand with automatic grads from above, tensorflow also has some optimization methods implemented for you. Recall momentum & rmsprop? | y_guess = tf.Variable(np.zeros(2,dtype='float32'))
y_true = tf.range(1,3,dtype='float32')
loss = tf.reduce_mean((y_guess - y_true + tf.random_normal([2]))**2)
optimizer = tf.train.MomentumOptimizer(0.01,0.9).minimize(loss,var_list=y_guess)
#same, but more detailed:
#updates = [[tf.gradients(loss,y_guess)[0], y_gues... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Logistic regression exampleImplement the regular logistic regression training algorithmTips:* Use a shared variable for weights* X and y are potential inputs* Compile 2 functions: * `train_function(X, y)` - returns error and computes weights' new values __(through updates)__ * `predict_fun(X)` - just computes probabil... | from sklearn.datasets import load_digits
mnist = load_digits(2)
X,y = mnist.data, mnist.target
print("y [shape - %s]:" % (str(y.shape)), y[:10])
print("X [shape - %s]:" % (str(X.shape)))
print('X:\n',X[:3,:10])
print('y:\n',y[:10])
plt.imshow(X[0].reshape([8,8]))
# inputs and shareds
weights = <student.code_variable(... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Bonus: my1stNNYour ultimate task for this week is to build your first neural network [almost] from scratch and pure tensorflow.This time you will same digit recognition problem, but at a larger scale* images are now 28x28* 10 different digits* 50k samplesNote that you are not required to build 152-layer monsters here.... | from mnist import load_dataset
#[down]loading the original MNIST dataset.
#Please note that you should only train your NN on _train sample,
# _val can be used to evaluate out-of-sample error, compare models or perform early-stopping
# _test should be hidden under a rock untill final evaluation...
# But we both know i... | _____no_output_____ | MIT | 00_intro_nn/Tensorflow_intro.ipynb | fogside/DeepNLP |
Downloading and reading CORD19 corpusThis notebook downloads and reads the free cord19 corpus into one file. The notebook is hosted at IÜD, Heidelberg University github repository https://github.com/iued-uni-heidelberg/cord19CORD19 (covid-19) open-source corpus is available from https://www.semanticscholar.org/cord19... | !wget https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/historical_releases/cord-19_2021-08-30.tar.gz | --2021-09-05 10:29:02-- https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/historical_releases/cord-19_2021-08-30.tar.gz
Resolving ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com (ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com)... 52.92.128.170
Connecting to ai2-semanticscholar-cord-19.s3-us... | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Extracting cord-19 corpus, approximate time ~ 4 min | !tar -xvzf cord-19_2021-08-30.tar.gz | 2021-08-30/changelog
2021-08-30/cord_19_embeddings.tar.gz
2021-08-30/document_parses.tar.gz
2021-08-30/metadata.csv
| MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Removing initial archive to free some disk space | !rm cord-19_2021-08-30.tar.gz | _____no_output_____ | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Extracting document parsers, which contain individual articles in separate json files. This is expected to take ~ 12 min. | !tar -xvzf 2021-08-30/document_parses.tar.gz | _____no_output_____ | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Removing more files to save space: ~ 9 seconds | # removing more files to save space
!rm --recursive 2021-08-30
!rm --recursive document_parses/pdf_json | _____no_output_____ | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Reading json directory and merging into text file(s)Run this cell to create the class; then run the next cell to execute on the directory "document_parses/pmc_json"This is a class for reading a directory with json files and writing them to a single file or split into several text file, with "split_by_docs=N", N docume... | # -*- coding: utf-8 -*-
# Python script to open each file, read json input and copy to one text file for subsequent processing
import os, re, sys
import json
class clJsonDir2txt(object):
'''
@author Bogdan Babych, IÜD, Heidelberg University
@email bogdan [dot] babych [at] iued [dot] uni-heidelberg [dot] de... | _____no_output_____ | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
This cell will executre reading of json files into a single (or multiple) filesChange the value of "split_by_docs=0" to "split_by_docs=10000" or any number ; this will create several corpus files with 10000 or any required number fo documents per file, which you wish to have.Approximate execution time ~10 minFile size ... | # remove parameter textfilter='covid', to return all documents
OJsonDir2txt = clJsonDir2txt("document_parses/pmc_json", output_file = 'covid19corpusFilterCOVID.txt', textfilter='covid', include_title = True, include_refs = False, split_by_docs=40000)
| 1000. Processing: PMC8328126.xml.json
2000. Processing: PMC8378831.xml.json
3000. Processing: PMC7885334.xml.json
4000. Processing: PMC7123675.xml.json
5000. Processing: PMC8237894.xml.json
6000. Processing: PMC4629194.xml.json
7000. Processing: PMC7423848.xml.json
8000. Processing: PMC8284347.xml.json
9000. Processing... | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
To see the number of words, paragraphs in your corpus you can use this command: | !wc covid19corpus.txt | _____no_output_____ | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
If you have split the text into parts, you can see the number of words in each part using this command: | !wc part* | 3899868 136307720 936593762 part1000000covid19corpus.txt
3861089 135312676 930249471 part1040000covid19corpus.txt
3966522 136553801 939515657 part1080000covid19corpus.txt
3941044 136273170 937283286 part1120000covid19corpus.txt
3713124 127131220 875458707 part1160000covid19corpus.txt
19381647... | MIT | cord19download2text.ipynb | iued-uni-heidelberg/DAAD-Training-2021 |
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se... | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Read in an Image | #reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra... | This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
| MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i... | import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
# return cv2.cvtColor(img,... | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.** | import os
os.listdir("test_images/") | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. | # TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images_output directory.
# Define Gaussian Filter parameters
GAUSSIAN_KERNEL_SIZE = 3
# End Gaussian Filter parameters
# Define Canny parameters
CANNY_LOW_THRESHOLD = 75
CANNY_HIGH_THRESHOLD = 150
# End Canny paramet... | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel... | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
# Utility function used to find out that challenge video has different image's size
def print_image_param(image):
print('This image is:', type(image), 'with dimensions:', image.shape)
... | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Let's try the one with the solid white lane on the right first ... | white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and... | [MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4
[MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
| MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. | HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output)) | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de... | yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start an... | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat... | challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and e... | _____no_output_____ | MIT | P1.ipynb | CollazzoD/CarND-LaneLines-P1 |
<div id="image_img" class="header_image_7"> Rock, Paper or Scissor Game - Train and Classify [Volume 2] Difficulty Level: ... | # Package that ensures a programatically interaction with operating system folder hierarchy.
from os import listdir
# Package used for clone a dictionary.
from copy import deepcopy
# Functions intended to extract some statistical parameters.
from numpy import max, std, average, sum, absolute
# With the following imp... | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
1 - Loading of all signals that integrates our training samples (storing them inside a dictionary)The acquired signals are stored inside a folder which can be accessed through a relative path "../../signal_samples/classification_game/data" 1.1 - Identification of the list of files/examples | # Transposition of data from signal files to a Python dictionary.
relative_path = "../../signal_samples/classification_game"
data_folder = "data"
# List of files (each file is a training example).
list_examples = listdir(relative_path + "/" + data_folder)
print(list_examples) | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
The first digit of filename identifies the class to which the training example belongs and the second digit is the trial number (<class>_<trial>.txt) 1.2 - Access the content of each file and store it on the respective dictionary entry | # Initialization of dictionary.
signal_dict = {}
# Scrolling through each entry in the list.
for example in list_examples:
if ".txt" in example: # Read only .txt files.
# Get the class to which the training example under analysis belong.
example_class = example.split("_")[0]
# Get the tria... | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
1.3 - Definition of the content of each channel | # Channels (CH1 Flexor digitorum superficialis | CH2 Aductor policis | CH3 Accelerometer axis Z).
emg_flexor = "CH1"
emg_adductor = "CH2"
acc_z = "CH3" | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
2 - Extraction of features according to the signal under analysisThe extracted values of each feature will be stored in a dictionary with the same hierarchical structure as "signal_dict" | # Clone "signal_dict".
features_dict = deepcopy(signal_dict)
# Navigate through "signal_dict" hierarchy.
list_classes = signal_dict.keys()
for class_i in list_classes:
list_trials = signal_dict[class_i].keys()
for trial in list_trials:
# Initialise "features_dict" entry content.
features_dict[c... | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
Each training array has the following structure/content:\[$\sigma_{emg\,flexor}$, $max_{emg\,flexor}$, $zcr_{emg\,flexor}$, $\sigma_{emg\,flexor}^{abs}$, $\sigma_{emg\,adductor}$, $max_{emg\,adductor}$, $zcr_{emg\,adductor}$, $\sigma_{emg\,adductor}^{abs}$, $\mu_{acc\,z}$, $\sigma_{acc\,z}$, $max_{acc\,z}$, $zcr_{acc\,... | # Package dedicated to the manipulation of json files.
from json import dump
filename = "classification_game_features.json"
# Generation of .json file in our previously mentioned "relative_path".
# [Generation of new file]
with open(relative_path + "/features/" + filename, 'w') as file:
dump(features_dict, file) | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
We reach the end of the "Classification Game" second volume. Now all the features of training examples are in our possession.If you are feeling your interest increasing, please jump to the next volume We hope that you have enjoyed this guide. biosignalsnotebooks is an environment in continuous expansion, so don't stop ... | from biosignalsnotebooks.__notebook_support__ import css_style_apply
css_style_apply()
%%html
<script>
// AUTORUN ALL CELLS ON NOTEBOOK-LOAD!
require(
['base/js/namespace', 'jquery'],
function(jupyter, $) {
$(jupyter.events).on("kernel_ready.Kernel", function () {
con... | _____no_output_____ | MIT | biosignalsnotebooks_notebooks/Categories/Train_And_Classify/classification_game_volume_2.ipynb | csavur/biosignalsnotebooks |
Build Features 1.Basic Featureslength, num of (signs, upper characters, lower character, number) | def build_features(df):
processed_features = df[["url"]].copy()
processed_features["path"] = processed_features["url"].map(
lambda x: urlparse(x).path + urlparse(x).params + urlparse(x).query + urlparse(x).fragment)
processed_features["path_len"] = processed_features["path"].map(
lambda x: l... | _____no_output_____ | MIT | page_ana/links_cluster.ipynb | ICEJM1020/DarkPatterns-StockInforPage |
2. Levenshteinbuuild a series distance between url and the website url 1. Edit Distance 2. Levenshtein Ratio 3. Jaro/Jaro-Winkler Dsitance(the answers are actually same) | import Levenshtein
def build_leven_features(df):
processed_features = []
for index, row in df.iterrows():
str1 = row['url']
str2 = row['website']
row['edit-dis'] = Levenshtein.distance(str1, str2)
row['leven-ratio'] = Levenshtein.ratio(str1, str2)
row['jw-dis'] = Levensht... | Matrix of PCs: (2552, 3)
Data matrix: (2552, 8)
3 singular values: [7.08981557 3.05313714 2.22082397]
| MIT | page_ana/links_cluster.ipynb | ICEJM1020/DarkPatterns-StockInforPage |
Clustering DBSCAN | # test dbscan
from sklearn.cluster import DBSCAN
from sklearn.utils import parallel_backend
with parallel_backend('threading'):
clusterer = DBSCAN(eps=0.005, min_samples=5, n_jobs=10, metric='euclidean')
cluster_labels = clusterer.fit(data_features)
potent_dp_links['cluster_dbscan'] = pd.Series(cluster_labels.... | Number of clusters: 178
Number of clusters: 163
| MIT | page_ana/links_cluster.ipynb | ICEJM1020/DarkPatterns-StockInforPage |
HDBSCAN | clusterer = HDBSCAN(min_cluster_size=5, metric='euclidean')
cluster_labels = clusterer.fit_predict(data_features)
pca_cluster_labels = clusterer.fit_predict(pca_data)
potent_dp_links['cluster_hdbscan'] = pd.Series(cluster_labels).values
potent_dp_links['pca_cluster_hdbscan'] = pd.Series(pca_cluster_labels).values
prin... | _____no_output_____ | MIT | page_ana/links_cluster.ipynb | ICEJM1020/DarkPatterns-StockInforPage |
3D Tic-Tac-Toe Objective and PrerequisitesTry this logic programming example to learn how to solve the problem of arranging X’s and O’s on a three-dimensional Tic-Tac-Toe board so as to minimize the number of completed lines or diagonals. This example will show you how a binary programming model can be used to capture... | import gurobipy as gp
from gurobipy import GRB
# tested with Python 3.7.0 & Gurobi 9.0 | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Model DeploymentWe first create a list of all possible lines and diagonals in a 3-D tic-tac-toe board. Each is represented as a Python tuple with 3 entries, where each entry gives the (i,j,k) position of the corresponding cell. There are 49 in total. | lines = []
size = 3
for i in range(size):
for j in range(size):
for k in range(size):
if i == 0:
lines.append(((0,j,k), (1,j,k), (2,j,k)))
if j == 0:
lines.append(((i,0,k), (i,1,k), (i,2,k)))
if k == 0:
lines.append(((i,j,0... | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Next we create our model and our decision variables. | model = gp.Model('Tic_Tac_Toe')
isX = model.addVars(size, size, size, vtype=GRB.BINARY, name="isX")
isLine = model.addVars(lines, vtype=GRB.BINARY, name="isLine") | Using license file c:\gurobi\gurobi.lic
| Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Now we create the constraints. The first states the board will contain 14 X's (and 13 O's): | x14 = model.addConstr(isX.sum() == 14) | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
The remaining constraints establish the relationship between the $isLine[]$ and $isX[]$ variables. A line is complete if all three cells contain the same symbol. In our model, this would correspond to three associated $isX[]$ variables summing to either 3 (all $X$) or 0 (all $O$). For our purposes, it is enough to e... | for line in lines:
model.addGenConstrIndicator(isLine[line], False, isX[line[0]] + isX[line[1]] + isX[line[2]] >= 1)
model.addGenConstrIndicator(isLine[line], False, isX[line[0]] + isX[line[1]] + isX[line[2]] <= 2) | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Finally, we set the optimization objective, which is to minimize the number of completed lines. | model.setObjective(isLine.sum()) | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Now we perform the optimization. | model.optimize() | Gurobi Optimizer version 9.1.0 build v9.1.0rc0 (win64)
Thread count: 4 physical cores, 8 logical processors, using up to 8 threads
Optimize a model with 1 rows, 76 columns and 27 nonzeros
Model fingerprint: 0xcbf7569f
Model has 98 general constraints
Variable types: 0 continuous, 76 integer (76 binary)
Coefficient stat... | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
--- ResultThe optimal solution completes only 4 lines or diagonals. We can visualize the result using matplotlib (we've peeled off the third dimension of the 3-D tic-tac-toe board). | import matplotlib.pyplot as plt
%matplotlib inline
fig, ax = plt.subplots(1, 3, figsize=(10,5))
for i in range(3):
ax[i].grid()
ax[i].set_xticks(range(4))
ax[i].set_yticks(range(4))
ax[i].tick_params(labelleft=False, labelbottom=False)
for cell in isX.keys():
if isX[cell].x > 0.5:
ax[c... | _____no_output_____ | Apache-2.0 | _beginning level/3d_tic_tac_toe/3d_tic_tac_toe.ipynb | ZedTDean/modeling-examples |
Trust Scores applied to MNIST It is important to know when a machine learning classifier's predictions can be trusted. Relying on the classifier's (uncalibrated) prediction probabilities is not optimal and can be improved upon. *Trust scores* measure the agreement between the classifier and a modified nearest neighbor... | import keras
from keras import backend as K
from keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Input, UpSampling2D
from keras.models import Model
from keras.utils import to_categorical
import matplotlib
%matplotlib inline
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np... | x_train shape: (60000, 28, 28) y_train shape: (60000,)
| Apache-2.0 | examples/trustscore_mnist.ipynb | SeptumCapital/alibi |
Prepare data: scale, reshape and categorize | x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
x_train = np.reshape(x_train, x_train.shape + (1,))
x_test = np.reshape(x_test, x_test.shape + (1,))
print('x_train shape:', x_train.shape, 'x_test shape:', x_test.shape)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
p... | _____no_output_____ | Apache-2.0 | examples/trustscore_mnist.ipynb | SeptumCapital/alibi |
Define and train model For this example we are not interested in optimizing model performance so a simple softmax classifier will do: | def sc_model():
x_in = Input(shape=(28, 28, 1))
x = Flatten()(x_in)
x_out = Dense(10, activation='softmax')(x)
sc = Model(inputs=x_in, outputs=x_out)
sc.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
return sc
sc = sc_model()
sc.summary()
sc.fit(x_train, y_train,... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 28, 28, 1) 0
________________________________________________________... | Apache-2.0 | examples/trustscore_mnist.ipynb | SeptumCapital/alibi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.