Jumat, 14 Februari 2020

Yield Function


def squares(N):
    for i in range(N):
        yield i*i
       
squares(10)
for n in squares(10):
    print(n)

list(squares(20))
+++++++++++++++++++++
OUT:
0
1
4
9
16
25
36
49
64
81
Out[107]:
[0,
 1,
 4,
 9,
 16,
 25,
 36,
 49,
 64,
 81,
 100,
 121,
 144,
 169,
 196,
 225,
 256,
 289,
 324,
 361]


Jika tidak diletakkan dalam fungsi maka akan error

for i in range(10):
        yield i*i


File "<ipython-input-109-a798d07d4d7b>", line 2
    yield i*i
    ^
SyntaxError: 'yield' outside function




IMPLEMENTASI

from keras.utils import to_categorical
from PIL import Image

def get_data_generator(df, indices, for_training, batch_size=16):
    images, ltipe = [], []
    while True:
        for i in indices:
            r = df.iloc[i]
            file, t= r['file'],r['tipe_id']
            im = Image.open(file)
            im = im.resize((IM_WIDTH, IM_HEIGHT))
            im = np.array(im) / 255.0
            images.append(im)
            ltipe.append(to_categorical(t, len(TIPE_ID_MAP)))
            if len(images) >= batch_size:
                yield np.array(images), [np.array(ltipe)]
                images,ltipe = [],[]
        if not for_training:
            break

Yaitu untuk membentuk data generator dar matrik image yang terkoleksi



REFF: https://rules.sonarsource.com/python/RSPEC-2711

Tidak ada komentar:

Posting Komentar