tf.ones_like() tf.zeros_like()用法

tf.ones_like | tf.zeros_like

tf.ones_like(tensor,dype=None,name=None)
tf.zeros_like(tensor,dype=None,name=None)
新建一个与给定的tensor类型大小一致的tensor,其所有元素为1和0

tensor=[[1, 2, 3], [4, 5, 6]] 
x = tf.ones_like(tensor) 
print(sess.run(x))

#[[1 1 1],
# [1 1 1]]
def train_step(real_ecg, dim): noise = tf.random.normal(dim) for i in range(disc_steps): with tf.GradientTape() as disc_tape: generated_ecg = generator(noise, training=True) real_output = discriminator(real_ecg, training=True) fake_output = discriminator(generated_ecg, training=True) disc_loss = discriminator_loss(real_output, fake_output) gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables) discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables)) ### for tensorboard ### disc_losses.update_state(disc_loss) fake_disc_accuracy.update_state(tf.zeros_like(fake_output), fake_output) real_disc_accuracy.update_state(tf.ones_like(real_output), real_output) ####################### with tf.GradientTape() as gen_tape: generated_ecg = generator(noise, training=True) fake_output = discriminator(generated_ecg, training=True) gen_loss = generator_loss(fake_output) gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables) generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables)) ### for tensorboard ### gen_losses.update_state(gen_loss) ####################### def train(dataset, epochs, dim): for epoch in tqdm(range(epochs)): for batch in dataset: train_step(batch, dim) disc_losses_list.append(disc_losses.result().numpy()) gen_losses_list.append(gen_losses.result().numpy()) fake_disc_accuracy_list.append(fake_disc_accuracy.result().numpy()) real_disc_accuracy_list.append(real_disc_accuracy.result().numpy()) ### for tensorboard ### # with disc_summary_writer.as_default(): # tf.summary.scalar('loss', disc_losses.result(), step=epoch) # tf.summary.scalar('fake_accuracy', fake_disc_accuracy.result(), step=epoch) # tf.summary.scalar('real_accuracy', real_disc_accuracy.result(), step=epoch) # with gen_summary_writer.as_default(): # tf.summary.scalar('loss', gen_losses.result(), step=epoch) disc_losses.reset_states() gen_losses.reset_states() fake_disc_accuracy.reset_states() real_disc_accuracy.reset_states() ####################### # Save the model every 5 epochs # if (epoch + 1) % 5 == 0: # generate_and_save_ecg(generator, epochs, seed, False) # checkpoint.save(file_prefix = checkpoint_prefix) # Generate after the final epoch display.clear_output(wait=True) generate_and_save_ecg(generator, epochs, seed, False)
06-08
def train_gan(generator, discriminator, gan, dataset, latent_dim, epochs): notes = get_notes() # 得到所有不重复的音调数目 num_pitch = len(set(notes)) network_input, network_output = prepare_sequences(notes, num_pitch) model = build_gan(network_input, num_pitch) # 输入,音符的数量,训练后的参数文件(训练的时候不用写) filepath = "03weights-{epoch:02d}-{loss:.4f}.hdf5" checkpoint = tf.keras.callbacks.ModelCheckpoint( filepath, # 保存参数文件的路径 monitor='loss', # 衡量的标准 verbose=0, # 不用冗余模式 save_best_only=True, # 最近出现的用monitor衡量的最好的参数不会被覆盖 mode='min' # 关注的是loss的最小值 ) for epoch in range(epochs): for real_images in dataset: # 训练判别器 noise = tf.random.normal((real_images.shape[0], latent_dim)) fake_images = generator(noise) with tf.GradientTape() as tape: real_pred = discriminator(real_images) fake_pred = discriminator(fake_images) real_loss = loss_fn(tf.ones_like(real_pred), real_pred) fake_loss = loss_fn(tf.zeros_like(fake_pred), fake_pred) discriminator_loss = real_loss + fake_loss gradients = tape.gradient(discriminator_loss, discriminator.trainable_weights) discriminator_optimizer.apply_gradients(zip(gradients, discriminator.trainable_weights)) # 训练生成器 noise = tf.random.normal((real_images.shape[0], latent_dim)) with tf.GradientTape() as tape: fake_images = generator(noise) fake_pred = discriminator(fake_images) generator_loss = loss_fn(tf.ones_like(fake_pred), fake_pred) gradients = tape.gradient(generator_loss, generator.trainable_weights) generator_optimizer.apply_gradients(zip(gradients, generator.trainable_weights)) gan.fit(network_input, np.ones((network_input.shape[0], 1)), epochs=100, batch_size=64) # 每 10 个 epoch 打印一次损失函数值 if (epoch + 1) % 10 == 0: print("Epoch:", epoch + 1, "Generator Loss:", generator_loss.numpy(), "Discriminator Loss:", discriminator_loss.numpy())
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值