code
stringlengths
17
6.64M
class UnityTask(): def __init__(self, name): self.brain = None self.brain_name = None self.env = self.create_unity_env() self.action_space = self.brain.vector_action_space_size self.observation_space = self.brain.vector_observation_space_size print(f'Action space {...
class PPOAgent_Unity(): def __init__(self, config): self.config = config self.task = UnityTask('reacher') self.network = PPONetwork(self.config.state_dim, self.config.action_dim, 1000).to('cuda:0') self.opt = torch.optim.Adam(self.network.parameters(), config.lr, amsgrad=True) ...
class UnityEnv(): def __init__(self, env_path, train_mode=True): self.brain = None self.brain_name = None self.train_mode = train_mode self.env = self.create_unity_env(env_path) self.action_space = self.brain.vector_action_space_size self.observation_space = self.b...
class Config(): DEVICE = (torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')) def __init__(self): self.device = ('cuda:0' if torch.cuda.is_available() else 'cpu') self.action_size = 2 self.state_dim = 8 self.action_dim = 2 self.play_only = Tru...
class Env_store(): def __init__(self, dim, state_dim): self.actions = tensor(dim) self.rewards = tensor(dim) self.advantage = tensor(dim) self.states = tensor(state_dim) self.network_output = None self.dones = tensor(dim) def populate(self, states, rewards, do...
class PPONetwork(nn.Module): 'Actor (Policy) Model.' def __init__(self, state_size, action_size, hidden_size): 'Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n ...
class Storage(): def __init__(self, size, keys=None): if (keys is None): keys = [] keys = (keys + ['s', 'a', 'r', 'm', 'v', 'q', 'pi', 'log_pi', 'ent', 'adv', 'ret', 'q_a', 'log_pi_a', 'mean']) self.keys = keys self.size = size self.reset() def add(self, d...
def random_sample(indices, batch_size): indices = np.asarray(np.random.permutation(indices)) batches = indices[:((len(indices) // batch_size) * batch_size)].reshape((- 1), batch_size) for batch in batches: (yield batch) r = (len(indices) % batch_size) if r: (yield indices[(- r):])
def tensor(x): if isinstance(x, torch.Tensor): return x x = torch.tensor(x, device=Config.DEVICE, dtype=torch.float32) return x
@jit def function(x): return x
@njit def njit_f(x): return x
@jit('int32(int32, int32)') def int32_sum(a, b): return (a + b)
@jit def int32_sum_r1(a: int, b: int): return (a + b)
def list_norm_inplace(buff): r_mean = np.mean(buff) r_std = np.std(buff) for ii in range(len(buff)): buff[ii] = ((buff[ii] - r_mean) / r_std)
def plot_durations(episode_durations): plt.figure(2) plt.clf() durations_t = TC.FloatTensor(episode_durations) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) if (len(durations_t) >= 100): means = durations_t.unfold(0, 100, 1)...
def plot_durations_ii(ii, episode_durations, ee, ee_duration=100): episode_durations.append((ii + 1)) if (((ee + 1) % ee_duration) == 0): clear_output() plot_durations(episode_durations)
class PGNET(nn.Module): def __init__(self, num_state): super(PGNET, self).__init__() self.fc_in = nn.Linear(num_state, 24) self.fc_hidden = nn.Linear(24, 36) self.fc_out = nn.Linear(36, 1) def forward(self, x): x = F.relu(self.fc_in(x)) x = F.relu(self.fc_hidd...
class PGNET_AGENT(PGNET): def run(self, env): for ee in range(self.num_episode): self.run_episode(env, ee) self.train_episode(ee)
def list_norm_inplace(buff): r_mean = np.mean(buff) r_std = np.std(buff) for ii in range(len(buff)): buff[ii] = ((buff[ii] - r_mean) / r_std)
def plot_durations(episode_durations): plt.figure(2) plt.clf() durations_t = TC.FloatTensor(episode_durations) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) if (len(durations_t) >= 100): means = durations_t.unfold(0, 100, 1)...
def plot_durations_ii(ii, episode_durations, ee, ee_duration=100): episode_durations.append((ii + 1)) if (((ee + 1) % ee_duration) == 0): clear_output() plot_durations(episode_durations)
class PGNET(nn.Module): def __init__(self, num_state): super(PGNET, self).__init__() self.fc_in = nn.Linear(num_state, 24) self.fc_hidden = nn.Linear(24, 36) self.fc_out = nn.Linear(36, 1) def forward(self, x): x = F.relu(self.fc_in(x)) x = F.relu(self.fc_hidd...
class PGNET_MACHINE(PGNET): def __init__(self, num_state, render_flag=False): self.forget_factor = 0.99 self.learning_rate = 0.01 self.num_episode = 5000 self.num_batch = 5 self.render_flag = render_flag self.steps_in_batch = 0 self.episode_durations = [] ...
def main(): env = gym.make('CartPole-v0') mypgnet = PGNET_MACHINE(env.observation_space.shape[0], render_flag=False) mypgnet.run(env) env.close()
def list_norm_inplace(buff): r_mean = np.mean(buff) r_std = np.std(buff) for ii in range(len(buff)): buff[ii] = ((buff[ii] - r_mean) / r_std)
def plot_durations(episode_durations): plt.figure(2) plt.clf() durations_t = TC.FloatTensor(episode_durations) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) if (len(durations_t) >= 100): means = durations_t.unfold(0, 100, 1)...
def plot_durations_ii(ii, episode_durations, ee, ee_duration=100): episode_durations.append((ii + 1)) if (((ee + 1) % ee_duration) == 0): clear_output() plot_durations(episode_durations)
class PGNET(nn.Module): def __init__(self, num_state): super(PGNET, self).__init__() self.fc_in = nn.Linear(num_state, 24) self.fc_hidden = nn.Linear(24, 36) self.fc_out = nn.Linear(36, 1) def forward(self, x): x = F.relu(self.fc_in(x)) x = F.relu(self.fc_hidd...
class PGNET_AGENT(PGNET): def __init__(self, num_state, render_flag=False): self.forget_factor = 0.99 self.learning_rate = 0.01 self.num_episode = 5000 self.num_batch = 5 self.render_flag = render_flag self.steps_in_batch = 0 self.episode_durations = [] ...
class CDENSE(Layer): def __init__(self, No, **kwargs): self.No = No super().__init__(**kwargs) def build(self, inshape_l): inshape = inshape_l[0] self.w_r = self.add_weight('w_r', (inshape[1], self.No), initializer=igu) self.w_i = self.add_weight('w_i', (inshape[1], s...
def modeling(input_shape): x_r = keras.layers.Input(input_shape) x_i = keras.layers.Input(input_shape) [y_r, y_i] = CDENSE(1, input_shape=(1,))([x_r, x_i]) return keras.models.Model([x_r, x_i], [y_r, y_i])
def cfit(model, x, y, **kwargs): x_l = [np.real(x), np.imag(x)] y_l = [np.real(y), np.imag(y)] return model.fit(x_l, y_l, **kwargs)
def cpredict(model, x, **kwargs): x_l = [np.real(x), np.imag(x)] y_l = model.predict(x_l) return (y_l[0] + (1j * y_l[1]))
def cget_weights(model): [w_r, w_i, b_r, b_i] = model.get_weights() return ([(w_r + (1j * w_i))], [(b_r + (1j * b_i))])
def cmain(): model = modeling((1,)) model.compile(keras.optimizers.sgd(), 'mse') x = (np.array([0, 1, 2, 3, 4]) + (1j * np.array([4, 3, 2, 1, 0]))) y = ((x * (2 + 1j)) + (1 + 2j)) h = cfit(model, x[:2], y[:2], epochs=5000, verbose=0) y_pred = cpredict(model, x[2:]) print('Targets:', y[2:])...
def ANN_models_func(Nin, Nh, Nout): x = layers.Input(shape=(Nin,)) h = layers.Activation('relu')(layers.Dense(Nh)(x)) y = layers.Activation('softmax')(layers.Dense(Nout)(h)) model = models.Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return...
def ANN_seq_func(Nin, Nh, Nout): model = models.Sequential() model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) model.add(layers.Dense(Nout, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
class ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') softmax = layers.Activation('softmax') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = sof...
class ANN_seq_class(models.Sequential): def __init__(self, Nin, Nh, Nout): super().__init__() self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) self.add(layers.Dense(Nout, activation='softmax')) self.compile(loss='categorical_crossentropy', optimizer='adam', metric...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = np_utils.to_categorical(y_train) Y_test = np_utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_...
def plot_acc(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['acc']) plt.plot(history['val_acc']) if (title is not None): plt.title(title) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Verification']...
def plot_loss(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['loss']) plt.plot(history['val_loss']) if (title is not None): plt.title(title) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Training', 'Verification'],...
def main(): Nin = 784 Nh = 100 number_of_class = 10 Nout = number_of_class model = ANN_seq_class(Nin, Nh, Nout) ((X_train, Y_train), (X_test, Y_test)) = Data_func() history = model.fit(X_train, Y_train, epochs=15, batch_size=100, validation_split=0.2) performace_test = model.evaluate(X...
class ANN(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = output(h) super().__init__(x, y) self.compile(l...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.boston_housing.load_data() scaler = preprocessing.MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) return ((X_train, y_train), (X_test, y_test))
def main(): Nin = 13 Nh = 5 Nout = 1 model = ANN(Nin, Nh, Nout) ((X_train, y_train), (X_test, y_test)) = Data_func() history = model.fit(X_train, y_train, epochs=100, batch_size=100, validation_split=0.2, verbose=2) performace_test = model.evaluate(X_test, y_test, batch_size=100) print...
class DNN(models.Sequential): def __init__(self, Nin, Nh_l, Nout): super().__init__() self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1')) self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2')) self.add(layers.Dense(Nout, activation=...
class DNN(models.Sequential): def __init__(self, Nin, Nh_l, Nout): super().__init__() self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1')) self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2')) self.add(layers.Dense(Nout, activation=...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = np_utils.to_categorical(y_train) Y_test = np_utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_...
def main(): Nin = 784 Nh_l = [100, 50] number_of_class = 10 Nout = number_of_class ((X_train, Y_train), (X_test, Y_test)) = Data_func() model = DNN(Nin, Nh_l, Nout) history = model.fit(X_train, Y_train, epochs=10, batch_size=100, validation_split=0.2) performace_test = model.evaluate(X...
class DNN(models.Sequential): def __init__(self, Nin, Nh_l, Pd_l, Nout): super().__init__() self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1')) self.add(layers.Dropout(Pd_l[0])) self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2'))...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.cifar10.load_data() Y_train = np_utils.to_categorical(y_train) Y_test = np_utils.to_categorical(y_test) (L, W, H, C) = X_train.shape X_train = X_train.reshape((- 1), ((W * H) * C)) X_test = X_test.reshape((- 1), ((W * H) * C)) ...
def main(Pd_l=[0.0, 0.0]): Nh_l = [100, 50] number_of_class = 10 Nout = number_of_class ((X_train, Y_train), (X_test, Y_test)) = Data_func() model = DNN(X_train.shape[1], Nh_l, Pd_l, Nout) history = model.fit(X_train, Y_train, epochs=100, batch_size=100, validation_split=0.2) performace_te...
class CNN(models.Sequential): def __init__(self, input_shape, num_classes): super().__init__() self.add(layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) self.add(layers.Conv2D(64, (3, 3), activation='relu')) self.add(layers.MaxPooling2D(pool_size=...
class DATA(): def __init__(self): num_classes = 10 ((x_train, y_train), (x_test, y_test)) = datasets.mnist.load_data() (img_rows, img_cols) = x_train.shape[1:] if (backend.image_data_format() == 'channels_first'): x_train = x_train.reshape(x_train.shape[0], 1, img_rows...
def main(): batch_size = 128 epochs = 10 data = DATA() model = CNN(data.input_shape, data.num_classes) history = model.fit(data.x_train, data.y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2) score = model.evaluate(data.x_test, data.y_test) print() print('Test loss:'...
class Machine(aicnn.Machine): def __init__(self): ((X, y), (x_test, y_test)) = datasets.cifar10.load_data() super().__init__(X, y, nb_classes=10)
def main(): m = Machine() m.run()
class Data(): def __init__(self, max_features=20000, maxlen=80): ((x_train, y_train), (x_test, y_test)) = imdb.load_data(num_words=max_features) x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_test = sequence.pad_sequences(x_test, maxlen=maxlen) (self.x_train, self.y_tr...
class RNN_LSTM(models.Model): def __init__(self, max_features, maxlen): x = layers.Input((maxlen,)) h = layers.Embedding(max_features, 128)(x) h = layers.LSTM(128, dropout=0.2, recurrent_dropout=0.2)(h) y = layers.Dense(1, activation='sigmoid')(h) super().__init__(x, y) ...
class Machine(): def __init__(self, max_features=20000, maxlen=80): self.data = Data(max_features, maxlen) self.model = RNN_LSTM(max_features, maxlen) def run(self, epochs=3, batch_size=32): data = self.data model = self.model print('Training stage') print('==...
def main(): m = Machine() m.run()
def main(): machine = Machine() machine.run(epochs=400)
class Machine(): def __init__(self): self.data = Dataset() shape = self.data.X.shape[1:] self.model = rnn_model(shape) def run(self, epochs=400): d = self.data (X_train, X_test, y_train, y_test) = (d.X_train, d.X_test, d.y_train, d.y_test) (X, y) = (d.X, d.y) ...
def rnn_model(shape): m_x = layers.Input(shape=shape) m_h = layers.LSTM(10)(m_x) m_y = layers.Dense(1)(m_h) m = models.Model(m_x, m_y) m.compile('adam', 'mean_squared_error') m.summary() return m
class Dataset(): def __init__(self, fname='international-airline-passengers.csv', D=12): data_dn = load_data(fname=fname) (X, y) = get_Xy(data_dn, D=D) (X_train, X_test, y_train, y_test) = model_selection.train_test_split(X, y, test_size=0.2, random_state=42) (self.X, self.y) = (X...
def load_data(fname='international-airline-passengers.csv'): dataset = pd.read_csv(fname, usecols=[1], engine='python', skipfooter=3) data = dataset.values.reshape((- 1)) plt.plot(data) plt.xlabel('Time') plt.ylabel('#Passengers') plt.title('Original Data') plt.show() data_dn = (((data...
def get_Xy(data, D=12): X_l = [] y_l = [] N = len(data) assert (N > D), 'N should be larger than D, where N is len(data)' for ii in range(((N - D) - 1)): X_l.append(data[ii:(ii + D)]) y_l.append(data[(ii + D)]) X = np.array(X_l) X = X.reshape(X.shape[0], X.shape[1], 1) ...
class AE(models.Model): def __init__(self, x_nodes=784, z_dim=36): x_shape = (x_nodes,) x = layers.Input(shape=x_shape) z = layers.Dense(z_dim, activation='relu')(x) y = layers.Dense(x_nodes, activation='sigmoid')(z) super().__init__(x, y) self.x = x self.z...
def show_ae(autoencoder): encoder = autoencoder.Encoder() decoder = autoencoder.Decoder() encoded_imgs = encoder.predict(X_test) decoded_imgs = decoder.predict(encoded_imgs) n = 10 plt.figure(figsize=(20, 6)) for i in range(n): ax = plt.subplot(3, n, (i + 1)) plt.imshow(X_t...
def main(): x_nodes = 784 z_dim = 36 autoencoder = AE(x_nodes, z_dim) history = autoencoder.fit(X_train, X_train, epochs=10, batch_size=256, shuffle=True, validation_data=(X_test, X_test)) plot_acc(history, '(a) ν•™μŠ΅ 경과에 λ”°λ₯Έ 정확도 λ³€ν™” 좔이') plt.show() plot_loss(history, '(b) ν•™μŠ΅ 경과에 λ”°λ₯Έ 손싀값 λ³€ν™” 좔이')...
def Conv2D(filters, kernel_size, padding='same', activation='relu'): return layers.Conv2D(filters, kernel_size, padding=padding, activation=activation)
class AE(models.Model): def __init__(self, org_shape=(1, 28, 28)): original = layers.Input(shape=org_shape) x = Conv2D(4, (3, 3))(original) x = layers.MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3))(x) x = layers.MaxPooling2D((2, 2), padding='same')(x) ...
def show_ae(autoencoder, data): x_test = data.x_test decoded_imgs = autoencoder.predict(x_test) print(decoded_imgs.shape, data.x_test.shape) if (backend.image_data_format() == 'channels_first'): (N, n_ch, n_i, n_j) = x_test.shape else: (N, n_i, n_j, n_ch) = x_test.shape x_test ...
def main(epochs=20, batch_size=128): data = DATA() autoencoder = AE(data.input_shape) history = autoencoder.fit(data.x_train, data.x_train, epochs=epochs, batch_size=batch_size, shuffle=True, validation_split=0.2) plot_acc(history, '(a) 정확도 ν•™μŠ΅ 곑선') plt.show() plot_loss(history, '(b) 손싀 ν•™μŠ΅ 곑선')...
def add_decorate(x): '\n axis = -1 --> last dimension in an array\n ' m = K.mean(x, axis=(- 1), keepdims=True) d = K.square((x - m)) return K.concatenate([x, d], axis=(- 1))
def add_decorate_shape(input_shape): shape = list(input_shape) assert (len(shape) == 2) shape[1] *= 2 return tuple(shape)
def model_compile(model): return model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
class GAN(): def __init__(self, ni_D, nh_D, nh_G): self.ni_D = ni_D self.nh_D = nh_D self.nh_G = nh_G self.D = self.gen_D() self.G = self.gen_G() self.GD = self.make_GD() def gen_D(self): ni_D = self.ni_D nh_D = self.nh_D D = models.Seq...
class Data(): def __init__(self, mu, sigma, ni_D): self.real_sample = (lambda n_batch: np.random.normal(mu, sigma, (n_batch, ni_D))) self.in_sample = (lambda n_batch: np.random.rand(n_batch, ni_D))
class Machine(): def __init__(self, n_batch=10, ni_D=100): data_mean = 4 data_stddev = 1.25 self.n_iter_D = 1 self.n_iter_G = 5 self.data = Data(data_mean, data_stddev, ni_D) self.gan = GAN(ni_D=ni_D, nh_D=50, nh_G=50) self.n_batch = n_batch def train_...
class GAN_Pure(GAN): def __init__(self, ni_D, nh_D, nh_G): '\n Discriminator input is not added\n ' super().__init__(ni_D, nh_D, nh_G) def gen_D(self): ni_D = self.ni_D nh_D = self.nh_D D = models.Sequential() D.add(Dense(nh_D, activation='relu',...
class Machine_Pure(Machine): def __init__(self, n_batch=10, ni_D=100): data_mean = 4 data_stddev = 1.25 self.data = Data(data_mean, data_stddev, ni_D) self.gan = GAN_Pure(ni_D=ni_D, nh_D=50, nh_G=50) self.n_batch = n_batch
def main(): machine = Machine(n_batch=1, ni_D=100) machine.run(n_repeat=200, n_show=200, n_test=100)
class Machine(aigen.Machine_Generator): def __init__(self): ((x_train, y_train), (x_test, y_test)) = datasets.cifar10.load_data() (_, X, _, y) = model_selection.train_test_split(x_train, y_train, test_size=0.02) X = X.astype(float) gen_param_dict = {'rotation_range': 10} s...
def main(): m = Machine() m.run()
class Machine(aiprt.Machine_Generator): def __init__(self): ((x_train, y_train), (x_test, y_test)) = datasets.cifar10.load_data() (_, X, _, y) = model_selection.train_test_split(x_train, y_train, test_size=0.02) X = X.astype(float) super().__init__(X, y, nb_classes=10)
def main(): m = Machine() m.run()
def Lambda_with_lambda(): from keras.layers import Lambda, Input from keras.models import Model x = Input((1,)) y = Lambda((lambda x: (x + 1)))(x) m = Model(x, y) yp = m.predict_on_batch([1, 2, 3]) print('np.array([1,2,3]) + 1:') print(yp)
def Lambda_function(): from keras.layers import Lambda, Input from keras.models import Model def kproc(x): return (((x ** 2) + (2 * x)) + 1) def kshape(input_shape): return input_shape x = Input((1,)) y = Lambda(kproc, kshape)(x) m = Model(x, y) yp = m.predict_on_batc...
def Backend_for_Lambda(): from keras.layers import Lambda, Input from keras.models import Model from keras import backend as K def kproc_concat(x): m = K.mean(x, axis=1, keepdims=True) d1 = K.abs((x - m)) d2 = K.square((x - m)) return K.concatenate([x, d1, d2], axis=1)...
def TF_for_Lamda(): from keras.layers import Lambda, Input from keras.models import Model import tensorflow as tf def kproc_concat(x): m = tf.reduce_mean(x, axis=1, keep_dims=True) d1 = tf.abs((x - m)) d2 = tf.square((x - m)) return tf.concat([x, d1, d2], axis=1) ...
def main(): print('Lambda with lambda') Lambda_with_lambda() print('Lambda function') Lambda_function() print('Backend for Lambda') Backend_for_Lambda() print('TF for Lambda') TF_for_Lamda()
class SFC(Layer): def __init__(self, No, **kwargs): self.No = No super().__init__(**kwargs) def build(self, inshape): self.w = self.add_weight('w', (inshape[1], self.No), initializer=igu) self.b = self.add_weight('b', (self.No,), initializer=iz) super().build(inshape)...
def main(): x = np.array([0, 1, 2, 3, 4]) y = ((x * 2) + 1) model = keras.models.Sequential() model.add(SFC(1, input_shape=(1,))) model.compile('SGD', 'mse') model.fit(x[:2], y[:2], epochs=1000, verbose=0) print('Targets:', y[2:]) print('Predictions:', model.predict(x[2:]).flatten())
class DNN(): def __init__(self, Nin, Nh_l, Nout): self.X_ph = tf.placeholder(tf.float32, shape=(None, Nin)) self.L_ph = tf.placeholder(tf.float32, shape=(None, Nout)) H = Dense(Nh_l[0], activation='relu')(self.X_ph) H = Dropout(0.5)(H) H = Dense(Nh_l[1], activation='relu')...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = np_utils.to_categorical(y_train) Y_test = np_utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_...
def run(model, data, sess, epochs, batch_size=100): ((X_train, Y_train), (X_test, Y_test)) = data sess.run(model.Init_tf) with sess.as_default(): N_tr = X_train.shape[0] for epoch in range(epochs): for b in range((N_tr // batch_size)): X_tr_b = X_train[(batch_si...
def main(): Nin = 784 Nh_l = [100, 50] number_of_class = 10 Nout = number_of_class data = Data_func() model = DNN(Nin, Nh_l, Nout) run(model, data, sess, 10, 100)
class CNN(Model): def __init__(model, nb_classes, in_shape=None): model.nb_classes = nb_classes model.in_shape = in_shape model.build_model() super().__init__(model.x, model.y) model.compile() def build_model(model): nb_classes = model.nb_classes in_sh...