tensorflow中显示 list 无法使用tf.cast()

num_examples = 10000
num_iter = int(math.ceil(num_examples / batch_size))
true_count = 0
total_samples_count = num_iter * batch_size
step = 0
while step < num_iter:
    image_batch,label_batch = sess.run([images_test,labels_test])
    predictions = sess.run([top_k_op],feed_dict={image_holder: image_batch, label_holder:label_batch})
    true_count += np.sum(predictions)
    step += 1
precision = true_count/total_samples_count
print('precision @ 1 = %.3f' %precision)

其中

1.情况1

    predictions = sess.run(top_k_op, feed_dict={image_holder: image_batch,label_holder:label_batch})
    print(type(predictions))

打印值为<class ‘numpy.ndarray’>,tensor经过Session.run()自动生成numpy数组

参考:https://stackoverflow.com/questions/34097281/how-can-i-convert-a-tensor-into-a-numpy-array-in-tensorflow

2.情况2

    predictions = sess.run([top_k_op],  feed_dict={image_holder: image_batch,label_holder:label_batch})
    print(type(predictions))

打印值为<class ‘list’>
当使用 tf.cast()predictions进行变换时,出现错误:

ValueError: Argument must be a dense tensor: [array([False, True, False.......])]- got shape [1,128], but wanted [1].

问题
[ ] 使得原本的array变成了list(这种[array([False, True, False…])]),这种list+array的混搭模式是list。
解决方法
再将其转换为array就可以了:predictions = np.array(predictions)然后再使用 tf.cast() 就没有问题了。或者像情况1一样去除 [top_k_op] 外的 [ ]

参考: https://blog.csdn.net/u010698086/article/details/78175933
(不知道理解的有没有问题。。)

解释以下这段代码:import tensorflow as tf gpus =tf.config.experimental.list_physical_devices(device_type='GPU') tf.config.experimental.set_virtual_device_configuration(gpus[0],[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)]) #import scipy.io as sio import pickle import os,random import matplotlib.pyplot as plt #import scipy.stats from tensorflow import losses from tensorflow.keras import Model from tensorflow.keras import layers import matplotlib.pyplot as plt import tensorflow as tf import numpy as np #import scipy.io as sio #import scipy.stats import math import os import pdb from tensorflow import losses from model import ResNet18 from re_dataset_real import train_image1,train_label1,test_image1,test_label1,val_image1,val_label1 from re_dataset_imag import train_image2,train_label2,test_image2,test_label2,val_image2,val_label2 def phsical_loss(y_true, y_pred): y_true =tf.cast(y_true, y_pred.dtype) loss_real=tf.keras.losses.MSE(y_true[0],y_pred[0]) loss_img= tf.keras.losses.MSE(y_true[1],y_pred[1]) amp_ture=tf.pow(y_true[0],2)+tf.pow(y_true[1],2) amp_pred=tf.pow(y_pred[0],2)+tf.pow(y_pred[1],2) loss_amp=tf.keras.losses.MSE(amp_ture,amp_pred) return loss_real+loss_img+loss_amp#两个子模型各加一个完整约束 def angle_loss(y_true, y_pred): y_true = tf.cast(y_true, y_pred.dtype) img_ture=tf.atan2(y_true[1],y_true[0]) img_pred=tf.atan2(y_pred[1],y_pred[0]) return tf.keras.losses.MAE(img_ture,img_pred) def amp_loss(y_true, y_pred): y_true = tf.cast(y_true, y_pred.dtype) amp_ture=tf.pow(y_true[0],2)+tf.pow(y_true[1],2) amp_pred=tf.pow(y_pred[0],2)+tf.pow(y_pred[1],2) loss_phsical=tf.keras.losses.MSE(amp_ture,amp_pred) return loss_phsical model_in=tf.keras.Input((16,16,1)) model_real_out=ResNet18([2,2,2,2])(model_in) model_img_out=ResNet18([2,2,2,2])(model_in) model_all=tf.keras.Model(model_in,[model_real_out,model_img_out]) model_all.compile(loss=phsical_loss, optimizer=tf.keras.optimizers.Adam(tf.keras.optimizers.schedules.InverseTimeDecay( 0.001, decay_steps=250*25, decay_rate=1, staircase=False)), metrics=['mse']) checkpoint_save_path= "C:\\Users\\Root\\Desktop\\bysj\\model_all.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('------------------load model all---------------------') model_all.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True,save_best_only=True)
最新发布
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值