markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืื•ืžื ื ืœืžื“ื ื• ืฉืœื ืื•ืžืจื™ื ืื™ื›ืก ืขืœ ืคื•ื ืงืฆื™ื•ืช, ืื‘ืœ ืžื” ืงื•ืจื” ืคื”? </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ื‘ื ื™ื’ื•ื“ ืœืคื•ื ืงืฆื™ื•ืช ืจื’ื™ืœื•ืช, ืงืจื™ืื” ืœึพgenerator ืœื ืžื—ื–ื™ืจื” ืขืจืš ืžื™ื™ื“.<br> ื‘ืžืงื•ื ืขืจืš ื”ื™ื ืžื—ื–ื™ืจื” ืžืขื™ืŸ ืกืžืŸ,...
our_generator = silly_generator()
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื‘ืขืงื‘ื•ืช ื”ืงืจื™ืื” ืœึพ<code>silly_generator</code> ื ื•ืฆืจ ืœื ื• ืกืžืŸ ืฉืžืฆื‘ื™ืข ื›ืจื’ืข ืขืœ ื”ืฉื•ืจื” <code>a = 1</code>.<br> ื”ืžื™ื ื•ื— ื”ืžืงืฆื•ืขื™ ืœืกืžืŸ ื”ื–ื” ื”ื•ื <dfn>generator iterator</dfn>. </p> <img src="images/silly_generator1.png?v=1" width="300px" style="displa...
next_value = next(our_generator) print(next_value)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื›ื“ื™ ืœื”ื‘ื™ืŸ ืžื” ื”ืชืจื—ืฉ ื ืฆื˜ืจืš ืœื”ื‘ื™ืŸ ืฉื ื™ ื“ื‘ืจื™ื ื—ืฉื•ื‘ื™ื ืฉืงืฉื•ืจื™ื ืœึพgenerators:<br> </p> <ol style="text-align: right; direction: rtl; float: right; clear: both;"> <li>ืงืจื™ืื” ืœึพ<code>next</code> ื”ื™ื ื›ืžื• ืœื—ื™ืฆื” ืขืœ "ื ื’ืŸ" (Play) โ€“ ื”ื™ื ื’ื•ืจืžืช ืœืกืžืŸ ืœืจื•ืฅ ืขื“...
print(next(our_generator))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื ืกื›ื ืžื” ืงืจื” ืขื“ ืขื›ืฉื™ื•: </p> <ol style="text-align: right; direction: rtl; float: right; clear: both;"> <li>ื”ื’ื“ืจื ื• ืคื•ื ืงืฆื™ื” ื‘ืฉื <var>silly_generator</var>, ืฉืืžื•ืจื” ืœื”ื—ื–ื™ืจ ืืช ื”ืขืจื›ื™ื <samp>1</samp>, <samp>2</samp> ื•ึพ<samp dir="ltr">[1, 2, 3]</...
print(next(our_generator))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื™ื•ืคื™! ื”ื›ืœ ื”ืœืš ื›ืžืฆื•ืคื”.<br> ืื‘ืœ ืžื” ืฆื•ืคืŸ ืœื ื• ื”ืขืชื™ื“?<br> ื‘ืคืขื ื”ื‘ืื” ืฉื ื‘ืงืฉ ืขืจืš ืžื”ืคื•ื ืงืฆื™ื”, ื”ืกืžืŸ ืฉืœื ื• ื™ืจื•ืฅ ื”ืœืื” ื•ืœื ื™ื™ืชืงืœ ื‘ึพ<code>yield</code>.<br> ื‘ืžืงืจื” ื›ื–ื”, ื ืงื‘ืœ ืฉื’ื™ืืช <var>StopIteration</var>, ืฉืžื‘ืฉืจืช ืœื ื• ืฉึพ<code>next</code> ืœื ื”ืฆืœื™ื— ืœื—...
print(next(our_generator))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืžื•ื‘ืŸ ืฉืื™ืŸ ืกื™ื‘ื” ืœื”ื™ืœื—ืฅ.<br> ื‘ืžืงืจื” ื”ื–ื” ืืคื™ืœื• ืœื ืžื“ื•ื‘ืจ ื‘ืžืฉื”ื• ืจืข โ€“ ืคืฉื•ื˜ ื›ื™ืœื™ื ื• ืืช ื›ืœ ื”ืขืจื›ื™ื ืžื”ึพgenerator iterator ืฉืœื ื•.<br> ืคื•ื ืงืฆื™ื™ืช ื”ึพgenerator ืขื“ื™ื™ืŸ ืงื™ื™ืžืช!<br> ืืคืฉืจ ืœื™ืฆื•ืจ ืขื•ื“ generator iterator ืื ื ืจืฆื”, ื•ืœืงื‘ืœ ืืช ื›ืœ ื”ืขืจื›ื™ื ืฉื ืžืฆืื™ื ื‘ื•...
our_generator = silly_generator() print(next(our_generator)) print(next(our_generator)) print(next(our_generator))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืื‘ืœ ื›ืฉื—ื•ืฉื‘ื™ื ืขืœ ื–ื”, ื–ื” ืงืฆืช ืžื’ื•ื—ืš.<br> ื‘ื›ืœ ืคืขื ืฉื ืจืฆื” ืœื”ืฉื™ื’ ืืช ื”ืขืจืš ื”ื‘ื ื ืฆื˜ืจืš ืœืจืฉื•ื <code>next</code>?<br> ื—ื™ื™ื‘ืช ืœื”ื™ื•ืช ื“ืจืš ื˜ื•ื‘ื” ื™ื•ืชืจ! </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">ื›ืœ generator ื”ื•ื ื’ื ...
our_generator = silly_generator() for item in our_generator: print(item)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืžื” ืžืชืจื—ืฉ ื›ืืŸ?<br> ืื ื—ื ื• ืžื‘ืงืฉื™ื ืžืœื•ืœืืช ื”ึพ<code>for</code> ืœืขื‘ื•ืจ ืขืœ ื”ึพgenerator iterator ืฉืœื ื•.<br> ื”ึพ<code>for</code> ืขื•ืฉื” ืขื‘ื•ืจื ื• ืืช ื”ืขื‘ื•ื“ื” ืื•ื˜ื•ืžื˜ื™ืช: </p> <ol style="text-align: right; direction: rtl; float: right; clear: both;"> <...
for item in our_generator: print(item)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืœืžื–ืœื ื•, ืœื•ืœืื•ืช <code>for</code> ื™ื•ื“ืขื•ืช ืœื˜ืคืœ ื‘ืขืฆืžืŸ ื‘ืฉื’ื™ืืช <code>StopIteration</code>, ื•ืœื›ืŸ ืฉื’ื™ืื” ืฉื›ื–ื• ืœื ืชืงืคื•ืฅ ืœื ื• ื‘ืžืงืจื” ื”ื–ื”. </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">ื”ืžืจืช ื˜ื™ืคื•ืกื™ื</span> <p style="text-...
our_generator = silly_generator() items = list(our_generator) print(items)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื‘ืงื•ื“ ืฉืœืžืขืœื”, ื”ืฉืชืžืฉื ื• ื‘ืคื•ื ืงืฆื™ื” <code>list</code> ืฉื™ื•ื“ืขืช ืœื”ืžื™ืจ ืขืจื›ื™ื iterableึพื™ื ืœืจืฉื™ืžื•ืช.<br> ืฉื™ืžื• ืœื‘ ืฉืžื” ืฉืœืžื“ื ื• ื‘ื ื•ื’ืข ืœ"ืกืžืŸ" ื™ื‘ื•ื ืœื™ื“ื™ ื‘ื™ื˜ื•ื™ ื’ื ื‘ื”ืžืจื•ืช: </p>
print(list(our_generator))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<span style="text-align: right; direction: rtl; float: right; clear: both;">ืฉื™ืžื•ืฉื™ื ืคืจืงื˜ื™ื™ื</span> <span style="text-align: right; direction: rtl; float: right; clear: both;">ื—ื™ืกื›ื•ืŸ ื‘ื–ื™ื›ืจื•ืŸ</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ื ื›ืชื•ื‘ ืคื•ื ืงืฆื™ื” ืจื’ื™ืœื” ืฉืžืงื‘ืœืช ืžืกืคืจ ืฉืœื, ื•ืžื—ื–ื™ืจื” ืจืฉื™ืž...
def my_range(upper_limit): numbers = [] current_number = 0 while current_number < upper_limit: numbers.append(current_number) current_number = current_number + 1 return numbers for number in my_range(1000): print(number)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื‘ืคื•ื ืงืฆื™ื” ื”ื–ื• ืื ื—ื ื• ื™ื•ืฆืจื™ื ืจืฉื™ืžืช ืžืกืคืจื™ื ื—ื“ืฉื”, ื”ืžื›ื™ืœื” ืืช ื›ืœ ื”ืžืกืคืจื™ื ื‘ื™ืŸ 0 ืœื‘ื™ืŸ ื”ืžืกืคืจ ืฉื”ื•ืขื‘ืจ ืœืคืจืžื˜ืจ <var>upper_limit</var>.<br> ืืš ื™ืฉื ื” ื‘ืขื™ื” ื—ืžื•ืจื” โ€“ ื”ืคืขืœืช ื”ืคื•ื ืงืฆื™ื” ื’ื•ืจืžืช ืœื ื™ืฆื•ืœ ืžืฉืื‘ื™ื ืจื‘ื™ื!<br> ืื ื ื›ื ื™ืก ื›ืืจื’ื•ืžื ื˜ 1,000 โ€“ ื ืฆื˜ืจืš ืœื”ื—ื–ื™ืง ืจืฉื™ืž...
def my_range(upper_limit): current_number = 0 while current_number < upper_limit: yield current_number current_number = current_number + 1 our_generator = my_range(1000) for number in our_generator: print(number)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืฉื™ืžื• ืœื‘ ื›ืžื” ื”ื’ืจืกื” ื”ื–ื• ืืœื’ื ื˜ื™ืช ื™ื•ืชืจ!<br> ื‘ื›ืœ ืคืขื ืื ื—ื ื• ืคืฉื•ื˜ ืฉื•ืœื—ื™ื ืืช ืขืจื›ื• ืฉืœ ืžืกืคืจ ืื—ื“ (<var>current_number</var>) ื”ื—ื•ืฆื”.<br> ื›ืฉืžื‘ืงืฉื™ื ืืช ื”ืขืจืš ื”ื‘ื ืžื”ึพgenerator iterator, ืคื•ื ืงืฆื™ื™ืช ื”ึพgenerator ื—ื•ื–ืจืช ืœืขื‘ื•ื“ ืžื”ื ืงื•ื“ื” ืฉื‘ื” ื”ื™ื ืขืฆืจื”:<br> ื”ื™...
def square_numbers(numbers): squared_numbers = [] for number in numbers: squared_numbers.append(number ** 2) return squared_numbers for number in square_numbers(my_range(1000)): print(number)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<span style="text-align: right; direction: rtl; float: right; clear: both;">ืชืฉื•ื‘ื•ืช ื—ืœืงื™ื•ืช</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ืœืขื™ืชื™ื ื ื™ืืœืฅ ืœื‘ืฆืข ื—ื™ืฉื•ื‘ ืืจื•ืš, ืฉื”ืฉืœืžืชื• ืชื™ืžืฉืš ื–ืžืŸ ืจื‘ ืžืื•ื“.<br> ื‘ืžืงืจื” ื›ื–ื”, ื ื•ื›ืœ ืœื”ืฉืชืžืฉ ื‘ึพgenerator ื›ื“ื™ ืœืงื‘ืœ ื—ืœืง ืžื”ืชื•ืฆืื” ื‘ื–ืžืŸ ืืžืช,<br> ื‘ื–ืžืŸ ืฉ...
def find_pythagorean_triples(upper_bound=10_000): pythagorean_triples = [] for c in range(3, upper_bound): for b in range(2, c): for a in range(1, b): if a ** 2 + b **2 == c ** 2: pythagorean_triples.append((a, b, c)) return pythagorean_triples for t...
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="ืื–ื”ืจื”!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: r...
def find_pythagorean_triples(upper_bound=10_000): for c in range(3, upper_bound): for b in range(2, c): for a in range(1, b): if a ** 2 + b **2 == c ** 2: yield a, b, c for triple in find_pythagorean_triples(): print(triple)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืื™ืš ื–ื” ืงืจื”? ืงื™ื‘ืœื ื• ืืช ื”ืชืฉื•ื‘ื” ื‘ืชื•ืš ืฉื‘ืจื™ืจ ืฉื ื™ื™ื”!<br> ื•ื‘ื›ืŸ, ื–ื” ืœื ืžื“ื•ื™ืง โ€“ ืงื™ื‘ืœื ื• ื—ืœืง ืžื”ืชืฉื•ื‘ื•ืช. ืฉื™ืžื• ืœื‘ ืฉื”ืงื•ื“ ืžืžืฉื™ืš ืœื”ื“ืคื™ืก :)<br> </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ืœื”ื–ื›ื™ืจื›ื, ื”ึพgenerator ืฉื•ืœื— ื...
def fibonacci(max_items): a = 1 b = 1 numbers = [1, 1] while len(numbers) < max_items: a, b = b, a + b # Unpacking numbers.append(b) return numbers for number in fibonacci(10): print(number)
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืœืขื•ืžืช ื–ืืช, ืœึพgenerators ืœื ื—ื™ื™ื‘ ืœื”ื™ื•ืช ืกื•ืฃ ืžื•ื’ื“ืจ.<br> ื ืฉืชืžืฉ ื‘ึพ<code>while True</code> ืฉืชืžื™ื“ ืžืชืงื™ื™ื, ื›ื“ื™ ืฉื‘ืกื•ืคื• ืฉืœ ื“ื‘ืจ โ€“ ืชืžื™ื“ ื ื’ื™ืข ืœึพ<code>yield</code>: </p>
def fibonacci(): a = 1 b = 1 numbers = [1, 1] while True: # ืชืžื™ื“ ืžืชืงื™ื™ื yield a a, b = b, a + b generator_iterator = fibonacci() for number in range(10): print(next(generator_iterator)) # ืื ื™ ื™ื›ื•ืœ ืœื‘ืงืฉ ื‘ืงืœื•ืช ืจื‘ื” ืืช 10 ื”ืื™ื‘ืจื™ื ื”ื‘ืื™ื ื‘ืกื“ืจื” for number in range(10): print...
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="ืื–ื”ืจื”!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: r...
def simple_generator(): yield 1 yield 2 yield 3
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื ื™ืฆื•ืจ ืฉื ื™ generator iterators ("ืกืžื ื™ื") ืฉื•ื ื™ื ืฉืžืฆื‘ื™ืขื™ื ืœืฉื•ืจื” ื”ืจืืฉื•ื ื” ืฉืœ ื”ึพgenerator ืฉืžื•ืคื™ืข ืœืžืขืœื”: </p>
first_gen = simple_generator() second_gen = simple_generator()
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื‘ืขื ื™ื™ืŸ ื–ื”, ื—ืฉื•ื‘ ืœื”ื‘ื™ืŸ ืฉื›ืœ ืื—ื“ ืžื”ึพgenerator iterators ื”ื•ื "ื—ืฅ" ื ืคืจื“ ืฉืžืฆื‘ื™ืข ืœืฉื•ืจื” ื”ืจืืฉื•ื ื” ื‘ึพ<var>simple_generator</var>.<br> ืื ื ื‘ืงืฉ ืžื›ืœ ืื—ื“ ืžื”ื ืœื”ื—ื–ื™ืจ ืขืจืš, ื ืงื‘ืœ ืžืฉื ื™ื”ื ืืช 1, ื•ืื•ืชื• ื—ืฅ ื“ืžื™ื•ื ื™ ื™ืขื‘ื•ืจ ื‘ืฉื ื™ ื”ึพgenerator iterators ืœื”ืžืชื™ืŸ ื‘ืฉื•ืจื” ื”ืฉื ...
print(next(first_gen)) print(next(second_gen))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ื ื•ื›ืœ ืœืงื“ื ืืช <var>first_gen</var>, ืœื“ื•ื’ืžื”, ืœืกื•ืฃ ื”ืคื•ื ืงืฆื™ื”: </p>
print(next(first_gen)) print(next(first_gen))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> ืื‘ืœ <var>second_gen</var> ื”ื•ื ื—ืฅ ื ืคืจื“, ืฉืขื“ื™ื™ืŸ ืžืฆื‘ื™ืข ืœืฉื•ืจื” ื”ืฉื ื™ื™ื” ืฉืœ ืคื•ื ืงืฆื™ื™ืช ื”ึพgenerator.<br> ืื ื ื‘ืงืฉ ืžืžื ื• ืืช ื”ืขืจืš ื”ื‘ื, ื”ื•ื ื™ืžืฉื™ืš ืืช ื”ืžืกืข ืžื”ืขืจืš <samp>2</samp>:<br> </p>
print(next(second_gen))
week05/3_Generators.ipynb
PythonFreeCourse/Notebooks
mit
Getting the data Here you can download the SVHN dataset. Run the cell above and it'll download to your machine.
from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm data_dir = 'data/' if not isdir(data_dir): raise Exception("Data directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
These SVHN files are .mat files typically used with Matlab. However, we can load them in with scipy.io.loadmat which we imported above.
trainset = loadmat(data_dir + 'train_32x32.mat') testset = loadmat(data_dir + 'test_32x32.mat')
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Here I'm showing a small sample of the images. Each of these is 32x32 with 3 color channels (RGB). These are the real images we'll pass to the discriminator and what the generator will eventually fake.
idx = np.random.randint(0, trainset['X'].shape[3], size=36) fig, axes = plt.subplots(6, 6, sharex=True, sharey=True, figsize=(5,5),) for ii, ax in zip(idx, axes.flatten()): ax.imshow(trainset['X'][:,:,:,ii], aspect='equal') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plt.subplots_adjust(wspace=0...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Here we need to do a bit of preprocessing and getting the images into a form where we can pass batches to the network. First off, we need to rescale the images to a range of -1 to 1, since the output of our generator is also in that range. We also have a set of test and validation images which could be used if we're tr...
def scale(x, feature_range=(-1, 1)): # scale to (0, 1) x = ((x - x.min())/(255 - x.min())) # scale to feature_range min, max = feature_range x = x * (max - min) + min return x class Dataset: def __init__(self, train, test, val_frac=0.5, shuffle=False, scale_func=None): split_id...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Network Inputs Here, just creating some placeholders like normal.
def model_inputs(real_dim, z_dim): inputs_real = tf.placeholder(tf.float32, (None, *real_dim), name='input_real') inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z') return inputs_real, inputs_z
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Generator Here you'll build the generator network. The input will be our noise vector z as before. Also as before, the output will be a $tanh$ output, but this time with size 32x32 which is the size of our SVHN images. What's new here is we'll use convolutional layers to create our new images. The first layer is a full...
def generator(z, output_dim, reuse=False, alpha=0.2, training=True): with tf.variable_scope('generator', reuse=reuse): # First fully connected layer x # Output layer, 32x32x3 logits = out = tf.tanh(logits) return out
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Discriminator Here you'll build the discriminator. This is basically just a convolutional classifier like you've build before. The input to the discriminator are 32x32x3 tensors/images. You'll want a few convolutional layers, then a fully connected layer for the output. As before, we want a sigmoid output, and you'll n...
def discriminator(x, reuse=False, alpha=0.2): with tf.variable_scope('discriminator', reuse=reuse): # Input layer is 32x32x3 x = logits = out = return out, logits
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Model Loss Calculating the loss like before, nothing new here.
def model_loss(input_real, input_z, output_dim, alpha=0.2): """ Get the loss for the discriminator and generator :param input_real: Images from the real dataset :param input_z: Z input :param out_channel_dim: The number of channels in the output image :return: A tuple of (discriminator loss, gen...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Optimizers Not much new here, but notice how the train operations are wrapped in a with tf.control_dependencies block so the batch normalization layers can update their population statistics.
def model_opt(d_loss, g_loss, learning_rate, beta1): """ Get optimization operations :param d_loss: Discriminator loss Tensor :param g_loss: Generator loss Tensor :param learning_rate: Learning Rate Placeholder :param beta1: The exponential decay rate for the 1st moment in the optimizer :ret...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Building the model Here we can use the functions we defined about to build the model as a class. This will make it easier to move the network around in our code since the nodes and operations in the graph are packaged in one object.
class GAN: def __init__(self, real_size, z_size, learning_rate, alpha=0.2, beta1=0.5): tf.reset_default_graph() self.input_real, self.input_z = model_inputs(real_size, z_size) self.d_loss, self.g_loss = model_loss(self.input_real, self.input_z, ...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Here is a function for displaying generated images.
def view_samples(epoch, samples, nrows, ncols, figsize=(5,5)): fig, axes = plt.subplots(figsize=figsize, nrows=nrows, ncols=ncols, sharey=True, sharex=True) for ax, img in zip(axes.flatten(), samples[epoch]): ax.axis('off') img = ((img - img.min())*255 / (img.max() ...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
And another function we can use to train our network. Notice when we call generator to create the samples to display, we set training to False. That's so the batch normalization layers will use the population statistics rather than the batch statistics. Also notice that we set the net.input_real placeholder when we run...
def train(net, dataset, epochs, batch_size, print_every=10, show_every=100, figsize=(5,5)): saver = tf.train.Saver() sample_z = np.random.uniform(-1, 1, size=(72, z_size)) samples, losses = [], [] steps = 0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for ...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Hyperparameters GANs are very senstive to hyperparameters. A lot of experimentation goes into finding the best hyperparameters such that the generator and discriminator don't overpower each other. Try out your own hyperparameters or read the DCGAN paper to see what worked for them. Exercise: Find hyperparameters to tr...
real_size = (32,32,3) z_size = 100 learning_rate = 0.001 batch_size = 64 epochs = 1 alpha = 0.01 beta1 = 0.9 # Create the network net = GAN(real_size, z_size, learning_rate, alpha=alpha, beta1=beta1) # Load the data and train the network here dataset = Dataset(trainset, testset) losses, samples = train(net, dataset, ...
dcgan-svhn/DCGAN_Exercises.ipynb
kitu2007/dl_class
mit
Setting up the Code Before we can plot our Dirichlet distributions, we need to do three things: Generate a set of x-y coordinates over our equilateral triangle Map the x-y coordinates to the 2-simplex coordinate space Compute Dir(ฮฑ)Dir(ฮฑ) for each point
def xy2bc(xy, tol=1.e-3): '''Converts 2D Cartesian coordinates to barycentric.''' s = [(corners[i] - midpoints[i]).dot(xy - midpoints[i]) / 0.75 for i in range(3)] return np.clip(s, tol, 1.0 - tol)
examples/python/Dirichlet distribution.ipynb
iaja/scalaLDAvis
apache-2.0
Gamma: $\Gamma \left( z \right) = \int\limits_0^\infty {x^{z - 1} e^{ - x} dx}$ $ \text{Dir}\left(\boldsymbol{\alpha}\right)\rightarrow \mathrm{p}\left(\boldsymbol{\theta}\mid\boldsymbol{\alpha}\right)=\frac{\Gamma\left(\sum_{i=1}^{k}\boldsymbol{\alpha}{i}\right)}{\prod{i=1}^{k}\Gamma\left(\boldsymbol{\alpha}{i}\right)...
class Dirichlet(object): def __init__(self, alpha): self._alpha = np.array(alpha) self._coef = gamma(np.sum(self._alpha)) / reduce(mul, [gamma(a) for a in self._alpha]) def pdf(self, x): '''Returns pdf value for `x`.''' return self._coef * reduce(mul, [xx ** (aa - 1) for (xx, aa)...
examples/python/Dirichlet distribution.ipynb
iaja/scalaLDAvis
apache-2.0
Download and Explore the Data
#downloading dataset !wget -nv -O ../data/PierceCricketData.csv https://ibm.box.com/shared/static/fjbsu8qbwm1n5zsw90q6xzfo4ptlsw96.csv df = pd.read_csv("../data/PierceCricketData.csv") df.head()
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<h6> Plot the Data Points </h6>
%matplotlib inline x_data, y_data = (df["Chirps"].values,df["Temp"].values) # plots the data points plt.plot(x_data, y_data, 'ro') # label the axis plt.xlabel("# Chirps per 15 sec") plt.ylabel("Temp in Farenhiet")
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
Looking at the scatter plot we can analyse that there is a linear relationship between the data points that connect chirps to the temperature and optimal way to infer this knowledge is by fitting a line that best describes the data. Which follows the linear equation: #### Ypred...
# Create place holders and Variables along with the Linear model. m = tf.Variable(3, dtype=tf.float32) c = tf.Variable(2, dtype=tf.float32) x = tf.placeholder(dtype=tf.float32, shape=x_data.size) y = tf.placeholder(dtype=tf.float32, shape=y_data.size) # Linear model y_pred = m * x + c
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#createvar" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="createvar" class="collapse"> ``` X = tf.placeholder(tf.float32, shape=(x_data.size)) Y = tf.placeholder(tf.float32,shape=(y_data.size)) # tf.Variable call creates a single updatable...
#create session and initialize variables session = tf.Session() session.run(tf.global_variables_initializer()) #get prediction with initial parameter values y_vals = session.run(y_pred, feed_dict={x: x_data}) #Your code goes here plt.plot(x_data, y_vals, label='Predicted') plt.scatter(x_data, y_data, color='red', lab...
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#matmul1" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="matmul1" class="collapse"> ``` pred = session.run(Ypred, feed_dict={X:x_data}) #plot initial prediction against datapoints plt.plot(x_data, pred) plt.plot(x_data, y_data, 'ro') # label...
loss = tf.reduce_mean(tf.squared_difference(y_pred*0.1, y*0.1))
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#matmul12" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="matmul12" class="collapse"> ``` # normalization factor nf = 1e-1 # seting up the loss function loss = tf.reduce_mean(tf.squared_difference(Ypred*nf,Y*nf)) ``` </div> Define an Optimiza...
# Your code goes here optimizer = tf.train.GradientDescentOptimizer(0.01) train_op = optimizer.minimize(loss)
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#matmul13" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="matmul13" class="collapse"> ``` optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) #optimizer = tf.train.AdagradOptimizer(0.01 ) # pass the loss function that optimizer ...
session.run(tf.global_variables_initializer())
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
Run session to train and predict the values of 'm' and 'c' for different training steps along with storing the losses in each step Get the predicted m and c values by running a session on Training a linear model. Also collect the loss for different steps to print and plot.
convergenceTolerance = 0.0001 previous_m = np.inf previous_c = np.inf steps = {} steps['m'] = [] steps['c'] = [] losses=[] for k in range(10000): ########## Your Code goes Here ########### _, _l, _m, _c = session.run([train_op, loss, m, c], feed_dict={x: x_data, y: y_data}) steps['m'].append(_m) ste...
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#matmul18" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="matmul18" class="collapse"> ``` # run a session to train , get m and c values with loss function _, _m , _c,_l = session.run([train, m, c,loss],feed_dict={X:x_data,Y:y_data}) ``` </d...
# Your Code Goes Here plt.plot(losses)
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
<div align="right"> <a href="#matmul199" class="btn btn-default" data-toggle="collapse">Click here for the solution</a> </div> <div id="matmul199" class="collapse"> ``` plt.plot(losses[:]) ``` </div>
y_vals_pred = y_pred.eval(session=session, feed_dict={x: x_data}) plt.scatter(x_data, y_vals_pred, marker='x', color='blue', label='Predicted') plt.scatter(x_data, y_data, label='GT', color='red') plt.legend() plt.ylabel('Temperature (Fahrenheit)') plt.xlabel('# Chirps per 15 s') session.close()
dl_tf_BDU/1.Intro_TF/ML0120EN-1.2-Exercise-LinearRegression.ipynb
santipuch590/deeplearning-tf
mit
Efficient serving <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/recommenders/examples/efficient_serving"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab...
!pip install -q tensorflow-recommenders !pip install -q --upgrade tensorflow-datasets
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
We also need to install scann: it's an optional dependency of TFRS, and so needs to be installed separately.
!pip install -q scann
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Set up all the necessary imports.
from typing import Dict, Text import os import pprint import tempfile import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_recommenders as tfrs
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
And load the data:
# Load the MovieLens 100K data. ratings = tfds.load( "movielens/100k-ratings", split="train" ) # Get the ratings data. ratings = (ratings # Retain only the fields we need. .map(lambda x: {"user_id": x["user_id"], "movie_title": x["movie_title"]}) # Cache for efficiency. ...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Before we can build a model, we need to set up the user and movie vocabularies:
user_ids = ratings.map(lambda x: x["user_id"]) unique_movie_titles = np.unique(np.concatenate(list(movies.batch(1000)))) unique_user_ids = np.unique(np.concatenate(list(user_ids.batch(1000))))
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
We'll also set up the training and test sets:
tf.random.set_seed(42) shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False) train = shuffled.take(80_000) test = shuffled.skip(80_000).take(20_000)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Model definition Just as in the basic retrieval tutorial, we build a simple two-tower model.
class MovielensModel(tfrs.Model): def __init__(self): super().__init__() embedding_dimension = 32 # Set up a model for representing movies. self.movie_model = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_movie_titles, mask_token=None), # We add an additi...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Fitting and evaluation A TFRS model is just a Keras model. We can compile it:
model = MovielensModel() model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Estimate it:
model.fit(train.batch(8192), epochs=3)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
And evaluate it.
model.evaluate(test.batch(8192), return_dict=True)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Approximate prediction The most straightforward way of retrieving top candidates in response to a query is to do it via brute force: compute user-movie scores for all possible movies, sort them, and pick a couple of top recommendations. In TFRS, this is accomplished via the BruteForce layer:
brute_force = tfrs.layers.factorized_top_k.BruteForce(model.user_model) brute_force.index_from_dataset( movies.batch(128).map(lambda title: (title, model.movie_model(title))) )
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Once created and populated with candidates (via the index method), we can call it to get predictions out:
# Get predictions for user 42. _, titles = brute_force(np.array(["42"]), k=3) print(f"Top recommendations: {titles[0]}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
On a small dataset of under 1000 movies, this is very fast:
%timeit _, titles = brute_force(np.array(["42"]), k=3)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
But what happens if we have more candidates - millions instead of thousands? We can simulate this by indexing all of our movies multiple times:
# Construct a dataset of movies that's 1,000 times larger. We # do this by adding several million dummy movie titles to the dataset. lots_of_movies = tf.data.Dataset.concatenate( movies.batch(4096), movies.batch(4096).repeat(1_000).map(lambda x: tf.zeros_like(x)) ) # We also add lots of dummy embeddings by ra...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
We can build a BruteForce index on this larger dataset:
brute_force_lots = tfrs.layers.factorized_top_k.BruteForce() brute_force_lots.index_from_dataset( tf.data.Dataset.zip((lots_of_movies, lots_of_movies_embeddings)) )
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
The recommendations are still the same
_, titles = brute_force_lots(model.user_model(np.array(["42"])), k=3) print(f"Top recommendations: {titles[0]}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
But they take much longer. With a candidate set of 1 million movies, brute force prediction becomes quite slow:
%timeit _, titles = brute_force_lots(model.user_model(np.array(["42"])), k=3)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
As the number of candidate grows, the amount of time needed grows linearly: with 10 million candidates, serving top candidates would take 250 milliseconds. This is clearly too slow for a live service. This is where approximate mechanisms come in. Using ScaNN in TFRS is accomplished via the tfrs.layers.factorized_top_k....
scann = tfrs.layers.factorized_top_k.ScaNN(num_reordering_candidates=100) scann.index_from_dataset( tf.data.Dataset.zip((lots_of_movies, lots_of_movies_embeddings)) )
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
The recommendations are (approximately!) the same
_, titles = scann(model.user_model(np.array(["42"])), k=3) print(f"Top recommendations: {titles[0]}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
But they are much, much faster to compute:
%timeit _, titles = scann(model.user_model(np.array(["42"])), k=3)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
In this case, we can retrieve the top 3 movies out of a set of ~1 million in around 2 milliseconds: 15 times faster than by computing the best candidates via brute force. The advantage of approximate methods grows even larger for larger datasets. Evaluating the approximation When using approximate top K retrieval mecha...
# Override the existing streaming candidate source. model.task.factorized_metrics = tfrs.metrics.FactorizedTopK( candidates=lots_of_movies_embeddings ) # Need to recompile the model for the changes to take effect. model.compile() %time baseline_result = model.evaluate(test.batch(8192), return_dict=True, verbose=Fa...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
We can do the same using ScaNN:
model.task.factorized_metrics = tfrs.metrics.FactorizedTopK( candidates=scann ) model.compile() # We can use a much bigger batch size here because ScaNN evaluation # is more memory efficient. %time scann_result = model.evaluate(test.batch(8192), return_dict=True, verbose=False)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
ScaNN based evaluation is much, much quicker: it's over ten times faster! This advantage is going to grow even larger for bigger datasets, and so for large datasets it may be prudent to always run ScaNN-based evaluation to improve model development velocity. But how about the results? Fortunately, in this case the resu...
print(f"Brute force top-100 accuracy: {baseline_result['factorized_top_k/top_100_categorical_accuracy']:.2f}") print(f"ScaNN top-100 accuracy: {scann_result['factorized_top_k/top_100_categorical_accuracy']:.2f}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
This suggests that on this artificial datase, there is little loss from the approximation. In general, all approximate methods exhibit speed-accuracy tradeoffs. To understand this in more depth you can check out Erik Bernhardsson's ANN benchmarks. Deploying the approximate model The ScaNN-based model is fully integrat...
lots_of_movies_embeddings # We re-index the ScaNN layer to include the user embeddings in the same model. # This way we can give the saved model raw features and get valid predictions # back. scann = tfrs.layers.factorized_top_k.ScaNN(model.user_model, num_reordering_candidates=1000) scann.index_from_dataset( tf.d...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
and then load it and serve, getting exactly the same results back:
_, titles = loaded(tf.constant(["42"])) print(f"Top recommendations: {titles[0][:3]}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
The resulting model can be served in any Python service that has TensorFlow and ScaNN installed. It can also be served using a customized version of TensorFlow Serving, available as a Docker container on Docker Hub. You can also build the image yourself from the Dockerfile. Tuning ScaNN Now let's look into tuning our S...
# Process queries in groups of 1000; processing them all at once with brute force # may lead to out-of-memory errors, because processing a batch of q queries against # a size-n dataset takes O(nq) space with brute force. titles_ground_truth = tf.concat([ brute_force_lots(queries, k=10)[1] for queries in test.batch(...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Our variable titles_ground_truth now contains the top-10 movie recommendations returned by brute-force retrieval. Now we can compute the same recommendations when using ScaNN:
# Get all user_id's as a 1d tensor of strings test_flat = np.concatenate(list(test.map(lambda x: x["user_id"]).batch(1000).as_numpy_iterator()), axis=0) # ScaNN is much more memory efficient and has no problem processing the whole # batch of 20000 queries at once. _, titles = scann(test_flat, k=10)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Next, we define our function that computes recall. For each query, it counts how many results are in the intersection of the brute force and the ScaNN results and divides this by the number of brute force results. The average of this quantity over all queries is our recall.
def compute_recall(ground_truth, approx_results): return np.mean([ len(np.intersect1d(truth, approx)) / len(truth) for truth, approx in zip(ground_truth, approx_results) ])
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
This gives us baseline recall@10 with the current ScaNN config:
print(f"Recall: {compute_recall(titles_ground_truth, titles):.3f}")
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
We can also measure the baseline latency:
%timeit -n 1000 scann(np.array(["42"]), k=10)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
Let's see if we can do better! To do this, we need a model of how ScaNN's tuning knobs affect performance. Our current model uses ScaNN's tree-AH algorithm. This algorithm partitions the database of embeddings (the "tree") and then scores the most promising of these partitions using AH, which is a highly optimized appr...
scann2 = tfrs.layers.factorized_top_k.ScaNN( model.user_model, num_leaves=1000, num_leaves_to_search=100, num_reordering_candidates=1000) scann2.index_from_dataset( tf.data.Dataset.zip((lots_of_movies, lots_of_movies_embeddings)) ) _, titles2 = scann2(test_flat, k=10) print(f"Recall: {compute_rec...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
However, as a tradeoff, our latency has also increased. This is because the partitioning step has gotten more expensive; scann picks the top 10 of 100 partitions while scann2 picks the top 100 of 1000 partitions. The latter can be more expensive because it involves looking at 10 times as many partitions.
%timeit -n 1000 scann2(np.array(["42"]), k=10)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
In general, tuning ScaNN search is about picking the right tradeoffs. Each individual parameter change generally won't make search both faster and more accurate; our goal is to tune the parameters to optimally trade off between these two conflicting goals. In our case, scann2 significantly improved recall over scann at...
scann3 = tfrs.layers.factorized_top_k.ScaNN( model.user_model, num_leaves=1000, num_leaves_to_search=70, num_reordering_candidates=400) scann3.index_from_dataset( tf.data.Dataset.zip((lots_of_movies, lots_of_movies_embeddings)) ) _, titles3 = scann3(test_flat, k=10) print(f"Recall: {compute_recall(...
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
scann3 delivers about a 3% absolute recall gain over scann while also delivering lower latency:
%timeit -n 1000 scann3(np.array(["42"]), k=10)
docs/examples/efficient_serving.ipynb
tensorflow/recommenders
apache-2.0
ๅค‰ๆ•ฐๅใจใƒ‡ใƒผใ‚ฟใฎๅ†…ๅฎนใƒกใƒข CENSUS: ๅธ‚ๅŒบ็”บๆ‘ใ‚ณใƒผใƒ‰(9ๆก) P: ๆˆ็ด„ไพกๆ ผ S: ๅฐ‚ๆœ‰้ข็ฉ L: ๅœŸๅœฐ้ข็ฉ R: ้ƒจๅฑ‹ๆ•ฐ RW: ๅ‰้ข้“่ทฏๅน…ๅ“ก CY: ๅปบ็ฏ‰ๅนด A: ๅปบ็ฏ‰ๅพŒๅนดๆ•ฐ(ๆˆ็ด„ๆ™‚) TS: ๆœ€ๅฏ„้ง…ใพใงใฎ่ท้›ข TT: ๆฑไบฌ้ง…ใพใงใฎๆ™‚้–“ ACC: ใ‚ฟใƒผใƒŸใƒŠใƒซ้ง…ใพใงใฎๆ™‚้–“ WOOD: ๆœจ้€ ใƒ€ใƒŸใƒผ SOUTH: ๅ—ๅ‘ใใƒ€ใƒŸใƒผ RSD: ไฝๅฑ…็ณปๅœฐๅŸŸใƒ€ใƒŸใƒผ CMD: ๅ•†ๆฅญ็ณปๅœฐๅŸŸใƒ€ใƒŸใƒผ IDD: ๅทฅๆฅญ็ณปๅœฐๅŸŸใƒ€ใƒŸใƒผ FAR: ๅปบใบใ„็އ FLR: ๅฎน็ฉ็އ TDQ: ๆˆ็ด„ๆ™‚็‚น(ๅ››ๅŠๆœŸ) X: ็ทฏๅบฆ Y:...
data = pd.read_csv("TokyoSingle.csv") data = data.dropna() CITY_NAME = data['CITY_CODE'].copy() CITY_NAME[CITY_NAME == 13101] = '01ๅƒไปฃ็”ฐๅŒบ' CITY_NAME[CITY_NAME == 13102] = "02ไธญๅคฎๅŒบ" CITY_NAME[CITY_NAME == 13103] = "03ๆธฏๅŒบ" CITY_NAME[CITY_NAME == 13104] = "04ๆ–ฐๅฎฟๅŒบ" CITY_NAME[CITY_NAME == 13105] = "05ๆ–‡ไบฌๅŒบ" CITY_NAME[CITY_NAME == ...
ไธๅ‹•็”ฃ/model2_1.ipynb
NlGG/Projects
mit
ๅธ‚ๅŒบ็”บๆ‘ๅˆฅใฎไปถๆ•ฐใ‚’้›†่จˆ
print(data['CITY_NAME'].value_counts()) vars = ['P', 'S', 'L', 'R', 'RW', 'A', 'TS', 'TT', 'WOOD', 'SOUTH', 'CMD', 'IDD', 'FAR', 'X', 'Y'] eq = fml_build(vars) y, X = dmatrices(eq, data=data, return_type='dataframe') CITY_NAME = pd.get_dummies(data['CITY_NAME']) TDQ = pd.get_dummies(data['TDQ'...
ไธๅ‹•็”ฃ/model2_1.ipynb
NlGG/Projects
mit
้’ใŒOLSใฎ่ชคๅทฎใ€็ท‘ใŒOLSใจๆทฑๅฑคๅญฆ็ฟ’ใ‚’็ต„ใฟๅˆใ‚ใ›ใŸ่ชคๅทฎใ€‚
model.compare() print(np.mean(model.error1)) print(np.mean(model.error2)) print(np.mean(np.abs(model.error1))) print(np.mean(np.abs(model.error2))) print(max(np.abs(model.error1))) print(max(np.abs(model.error2))) print(np.var(model.error1)) print(np.var(model.error2)) fig = plt.figure() ax = fig.add_subplot(111) ...
ไธๅ‹•็”ฃ/model2_1.ipynb
NlGG/Projects
mit
Sawtooth map Let's examine simple system where each next element is derived by previous element by the following rule: $$x_{n+1}={2 x_n}$$ where operator ${}$ means taking decimal part of a number.
#from math import trunc assert trunc(1.5) == 1.0 assert trunc(12.59) == 12.0 assert trunc(1) == 1.0 sawtooth = lambda x: round(2*x-trunc(2*x),8) sawtooth_borders = [pd.DataFrame([(0,0),(0.5,1)]), pd.DataFrame([(0.5,0),(1,1)])] for x0 in [0.4, 0.41, 0.42, 0.43]: cobweb_plot(take(iterator(sawtooth, x0=x0), n=30, sk...
Dynamical chaos.ipynb
schmooser/physics
mit
Logistic map Here we have very simple equation: $$x_{n+1} = k x_n (1 - x_n)$$ where $k$ is some fixed constant.
logistic = lambda k, x: k*x*(1-x) limits = [0,1] for k in [2.8, 3.2, 3.5, 3.9]: l = lambda x: logistic(k, x) cobweb_plot(take(iterator(l, x0=0.1), n=30, skip=500), limits, 'plot', boundary(l, limits)) # let's plot the bifurcation diagram dots = [] for k in linspace(2.5, 4, 0.001): for dot in set(take(ite...
Dynamical chaos.ipynb
schmooser/physics
mit
Define A Function, f(x)
# Define a function that, def f(x): # Outputs x multiplied by a random number drawn from a normal distribution return x * np.random.normal(size=1)[0]
mathematics/argmin_and_argmax.ipynb
tpin3694/tpin3694.github.io
mit
Create Some Values Of x
# Create some values of x xs = [1,2,3,4,5,6]
mathematics/argmin_and_argmax.ipynb
tpin3694/tpin3694.github.io
mit
Find The Argmin Of f(x)
#Define argmin that def argmin(f, xs): # Applies f on all the x's data = [f(x) for x in xs] # Finds index of the smallest output of f(x) index_of_min = data.index(min(data)) # Returns the x that produced that output return xs[index_of_min] # Run the argmin function argmin(f, xs)
mathematics/argmin_and_argmax.ipynb
tpin3694/tpin3694.github.io
mit
Check Our Results
print('x','|', 'f(x)') print('--------------') for x in xs: print(x,'|', f(x))
mathematics/argmin_and_argmax.ipynb
tpin3694/tpin3694.github.io
mit
We use experimental absorption coefficients of crystalline silicon and assume that the absorptivity follows Beer-Lambert's law. Also, we assume that every abosorped photons can be converted into electrons. In this case, having a 100% reflector on the back side of silicon can be thought of as doubling the thickness of s...
%matplotlib inline from pypvcell.photocurrent import conv_abs_to_qe,calc_jsc from pypvcell.illumination import Illumination from pypvcell.spectrum import Spectrum import numpy as np import matplotlib.pyplot as plt abs_file = "/Users/kanhua/Dropbox/Programming/pypvcell/legacy/si_alpha.csv" si_alpha = np.loadtxt(abs_f...
legacy/Enhancement in Jsc of back reflector.ipynb
kanhua/pypvcell
apache-2.0
Photocurrent with and without the back reflector
plt.semilogx(layer_t*1e6, jsc_baseline,hold=True,label="Si") plt.semilogx(layer_t*1e6,jsc_full_r,label="Si+100% mirror") plt.xlabel("thickness of Si substrate (um)") plt.ylabel("Jsc (A/m^2)") plt.legend(loc="best")
legacy/Enhancement in Jsc of back reflector.ipynb
kanhua/pypvcell
apache-2.0
Normlize the Jsc(Si+mirror) by Jsc(Si only)
plt.semilogx(layer_t*1e6,jsc_full_r/jsc_baseline) plt.xlabel("thickness of Si substrate (um)") plt.ylabel("Normalized Jsc enhancement") plt.savefig("jsc_enhancement.pdf") plt.show()
legacy/Enhancement in Jsc of back reflector.ipynb
kanhua/pypvcell
apache-2.0
We can see that the back reflector can be very effective when the thickness of silicon substrate is thin (< 1um). Silicon substrates with more than 10-um thicknesses cannot be benefited from this structure very well. This is the reason that photonic or plasmonic structure are useful for thin-film or ultra-thin-film sil...
# more detailed investigation plt.semilogx(layer_t*1e6,jsc_full_r/jsc_baseline) plt.xlabel("thickness of Si substrate (um)") plt.ylabel("Jsc enhancement (2x)") plt.xlim([100,1000]) plt.ylim([1.0,1.5]) plt.show()
legacy/Enhancement in Jsc of back reflector.ipynb
kanhua/pypvcell
apache-2.0
More audacious assumption Assume that somehow we have a novel reflector that can increase the optical absorption length by 10 times.
while not it.finished: t=it[0] #thickness of Si layer qe=conv_abs_to_qe(si_alpha_sp,t) jsc_baseline[it.index]=calc_jsc(Illumination("AM1.5g"), qe) # Assme 100% reflection on the back side, essentially doubling the thickness of silicon qe_full_r=conv_abs_to_qe(si_alpha_sp,t*10) jsc_full_r[it.i...
legacy/Enhancement in Jsc of back reflector.ipynb
kanhua/pypvcell
apache-2.0
repo_path is the path to a clone of swcarpentry/make-novice
repo_path = os.path.join( home, 'Dropbox/spikes/make-novice', ) assert os.path.exists(repo_path)
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
paths are the paths to child directories in a clone of swcarpentry/make-novice
paths = ( 'code', 'data', ) paths = ( code, data, ) = [os.path.join(repo_path, path) for path in paths] assert all(os.path.exists(path) for path in paths)
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Begin tutorial. Use the magic run to execute the Python script wordcount.py. The variables with '$' in front of them are the values of the Python variables in this notebook.
run $code/wordcount.py $data/books/isles.txt $repo_path/isles.dat
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
Use shell to examine the first 5 lines of the output file from running wordcount.py
!head -5 $repo_path/isles.dat
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit
We can see that the file consists of one row per word. Each row shows the word itself, the number of occurrences of that word, and the number of occurrences as a percentage of the total number of words in the text file.
run $code/wordcount.py $data/books/abyss.txt $repo_path/abyss.dat !head -5 $repo_path/abyss.dat
content/posts/makefile-tutorial/makefile_tutorial_0.ipynb
dm-wyncode/zipped-code
mit