在这篇文章中,我们将带领您了解TypeError:Fetchargument12434120.0hasinvalidtype,mustbeastringorTensor.在Tensorflow中的全貌
在这篇文章中,我们将带领您了解TypeError: Fetch argument 12434120.0 has invalid type
- TypeError: Fetch argument 12434120.0 has invalid type
, must be a string or Tensor. 在 Tensorflow 中 - "ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
- / image / Tensor Tensor(“ activation_5 / Softmax:0”,shape =(?, 4),dtype = float32)处的ValueError不是此图的元素
- 34-TypeError: BoxSizer.AddSpacer(): argument 1 has unexpected type ''tuple''
- cannot convert value of type 'String!' to expected argument type 'inout String'
TypeError: Fetch argument 12434120.0 has invalid type , must be a string or Tensor. 在 Tensorflow 中
如何解决TypeError: Fetch argument 12434120.0 has invalid type <class ''numpy.float32''>, must be a string or Tensor. 在 Tensorflow 中
我正在训练一个多元线性回归模型,出现这个错误代码。
TypeError: Fetch argument 12434120.0 has invalid type <class ''numpy.float32''>,must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)
我想知道这是什么意思... 和训练代码是这样的:
for step in range(100001):
cost_,hypo_,_ = sess.run([cost,hypothesis,train],Feed_dict={X: x_data,Y: y_data})
if step % 500 == 0:
print(''#'',step,''loss:'',cost_))
print(''-price of cabbage:'',hypo_[0])
解决方法
我重新启动了内核,它突然起作用了...我认为问题是名称''cost''重复了,所以我把它改成了''cost_''
"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
如何解决"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
我一直在研究用于图像分类的 CNN,但我一直遇到同样的错误,我的数据正在加载到数据帧中,但我无法将其转换为张量以将其输入 CNN。如您所见,我使用此代码将图片加载到数据框中:
for i in range(len(merged)):
full_path = merged.iloc[i][''Image Path Rel'']
filename = full_path[-22:-1] + ''G''
try:
img = img_to_array(load_img(''D:/Serengeti_Data/Compressed/Compressed/'' + filename,target_size=(32,32,3)))
except:
img = np.zeros((32,3),dtype=np.float32)
images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],''Image'' : img},ignore_index = True)
else:
images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],ignore_index = True)
然后,一旦我使用 load_img()
和 img_to_array()
加载了图像,我进行了重塑以获得所需的 (32,3) 形状。还通过将 Image 列除以 255 来标准化这些值。
然后我这样做是为了尝试将其转换为张量:
train_tf = tf.data.Dataset.from_tensor_slices(images[''Image''])
# Also tried this,but didn''t got the same results:
# train_tf = tf.convert_to_tensor(train_df[''Image''])
但不断收到错误:
ValueError: 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
我也尝试跳过它并立即尝试适应我们的模型,但得到了完全相同的错误:
trying_df = pd.DataFrame(images[''Image''])
target_df = pd.DataFrame(targets)
animal_model = models.Sequential()
animal_model.add(layers.Conv2D(30,kernel_size = (3,padding = ''valid'',activation = ''relu'',input_shape =(32,3)))
animal_model.add(layers.MaxPooling2D(pool_size=(1,1)))
animal_model.add(layers.Conv2D(60,kernel_size=(1,1),activation = ''relu''))
animal_model.add(layers.Flatten())
animal_model.add(layers.Dense(100,activation = ''relu''))
animal_model.add(layers.Dense(10,activation = ''softmax''))
## compiler to model
animal_model.compile(loss = ''categorical_crossentropy'',metrics = [''accuracy''],optimizer =''adam'')
## training the model
animal_model.fit(trying_df,target_df,batch_size = 128,epochs = 15)
animal_model.summary()
TensorFlow 版本:2.4.1
Numpy 版本:1.19.5
熊猫版本:1.0.1
解决方法
为了加载图像,您可以使用以下代码:
image = cv2.imread(filename)
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
为了调整图像的大小和缩放比例,最好让模型“嵌入”预处理功能。
IMG_SIZE = 180
resize_and_rescale = tf.keras.Sequential([
layers.experimental.preprocessing.Resizing(IMG_SIZE,IMG_SIZE),layers.experimental.preprocessing.Rescaling(1./255)
])
model = tf.keras.Sequential(
[
resize_and_rescale,layers.Conv2D(32,3,activation="relu"),layers.MaxPooling2D(),layers.Conv2D(64,layers.Conv2D(128,layers.Flatten(),layers.Dense(128,layers.Dense(len(class_names),activation="softmax"),]
)
model.compile(
optimizer="adam",loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=["accuracy"],)
注意:
处理图像时使用 tf.Data
而不是 numpy 数组。您可以使用以下代码作为示例:
https://github.com/alessiosavi/tensorflow-face-recognition/blob/90d4acbea8f79539826b50c82a63a7c151441a1a/dense_embedding.py#L155
/ image / Tensor Tensor(“ activation_5 / Softmax:0”,shape =(?, 4),dtype = float32)处的ValueError不是此图的元素
我正在构建图像处理分类器,并且此代码是用于预测整个代码正在运行的图像的图像类的API,但此行除外(pred =
model.predict_classes(test_image)),此API在Django框架中进行并且正在使用python 2.7
如果我像往常一样运行此代码(无需制作API),这一点就可以完美运行
def classify_image(request):if request.method == ''POST'' and request.FILES[''test_image'']: fs = FileSystemStorage() fs.save(request.FILES[''test_image''].name, request.FILES[''test_image'']) test_image = cv2.imread(''media/''+request.FILES[''test_image''].name) if test_image is not None: test_image = cv2.resize(test_image, (128, 128)) test_image = np.array(test_image) test_image = test_image.astype(''float32'') test_image /= 255 print(test_image.shape) else: print(''image didnt load'') test_image = np.expand_dims(test_image, axis=0) print(test_image) print(test_image.shape) pred = model.predict_classes(test_image) print(pred)return JsonResponse(pred, safe=False)
答案1
小编典典您的test_image和tensorflow模型的输入不匹配。
# Your image shape is (, , 3)test_image = cv2.imread(''media/''+request.FILES[''test_image''].name)if test_image is not None: test_image = cv2.resize(test_image, (128, 128)) test_image = np.array(test_image) test_image = test_image.astype(''float32'') test_image /= 255 print(test_image.shape)else: print(''image didnt load'')# Your image shape is (, , 4)test_image = np.expand_dims(test_image, axis=0)print(test_image)print(test_image.shape)pred = model.predict_classes(test_image)
以上仅为假设。如果要调试,我想您应该打印图像大小并与模型定义的第一个布局进行比较。并检查尺寸(宽度,高度,深度)是否匹配
34-TypeError: BoxSizer.AddSpacer(): argument 1 has unexpected type ''tuple''
TypeError: BoxSizer.AddSpacer(): argument 1 has unexpected type ''tuple''
这个错误很烦,折腾了好久;
原因有二:
1.因为它现在只能有一个参数了:
请看
2.因为你可能使用老版的wxFormBuilder产生的,而如果用新版的这会是:
bSizer1.Add( ( 0, 0), 1, wx.EXPAND, 5 )
新版下载链接:https://ci.appveyor.com/api/projects/jhasse/wxformbuilder-461d5/artifacts/wxFormBuilder_win32.zip?branch=master
不要在官网直接下载,感觉那个根本没跟新,跟新的已经放到了github上
主页面:https://github.com/wxFormBuilder/wxFormBuilder
官网:https://sourceforge.net/projects/wxformbuilder/
cannot convert value of type 'String!' to expected argument type 'inout String'
var area_big:String!var area_small:String!
var types = ""
var firstIn = true
provinces.forEach { (province) in
let count = province.children.count
for i in 0..<count{
if i == 0 && province.children[i].checked {
if area_big == nil {
area_big = province.children[i].attributes["name"]
}else{
area_big += "#" + province.children[i].attributes["name"]!
}
}
}
}
如果是按照上面那样写 ,会报如题错误。改为如下就可以了
var area_big:String! var area_small:String! var types = "" var firstIn = true provinces.forEach { (province) in let count = province.children.count for i in 0..<count{ if i == 0 && province.children[i].checked { if area_big == nil { area_big = province.children[i].attributes["name"] }else{ area_big = area_big + "#" + province.children[i].attributes["name"]! } } } }
我们今天的关于TypeError: Fetch argument 12434120.0 has invalid type
本文标签: