paddle.fluid.core.EnforceNotMet: Tensor holds the wrong type
Created by: jeff41404
程序如下,是1个简单的线性回归模型
import paddle
import paddle.fluid as fluid
import numpy as np
# init paddle
place = fluid.CPUPlace()
def inference_program():
# input data
x = fluid.layers.data(name='x', shape=[1], dtype='float32')
# define network
y_predict = fluid.layers.fc(input=x, size=1, act=None, bias_attr=True)
return y_predict
def train_program():
y_predict = inference_program()
# label
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
# cost function
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(cost)
#return avg_cost
accuracy = fluid.layers.accuracy(input=y_predict, label=y)
return [avg_cost, accuracy]
def optimizer_program():
# create optimizer
optimizer = fluid.optimizer.Momentum(momentum=0.6, learning_rate=0.001/64)
return optimizer
# create trainer
trainer = fluid.Trainer(
train_func=train_program,
optimizer=optimizer_program(),
place=place)
# event_handler to print training info
def event_handler(event):
if isinstance(event, fluid.EndStepEvent):
if event.step % 1 == 0:
print "Pass %d, Batch %d, Cost %f" % (
event.epoch, event.step, event.metrics[0])
#print "Pass %d, Batch %d, Cost %f, Acc %f" % (
#event.epoch, event.step, event.metrics[0], event.metrics[1])
# product model every 10 pass
if isinstance(event, fluid.EndEpochEvent):
if event.epoch % 100 == 0:
trainer.save_params('/exam/fluid_model/params_pass_%d.tar' % (event.epoch))
# define training dataset reader
def train_reader():
train_x = []
train_y = []
#train_x = np.array([[1], [2], [3], [5]])
#train_y = np.array([[6], [8], [10], [14]])
with open('/exam/train.data', 'r') as f:
lines=f.readlines()
for line in lines:
lineData=line.strip().split(',')
train_x.append(lineData[0])
train_y.append(lineData[1])
train_x=np.array(train_x).astype("float32")
train_y=np.array(train_y).astype("float32")
def reader():
for i in xrange(train_y.shape[0]):
yield train_x[i], train_y[i]
return reader
# define feeding map
feeding = ['x', 'y']
# training
trainer.train(
reader=paddle.batch(
train_reader(), batch_size=10),
feed_order=feeding,
event_handler=event_handler,
num_epochs=2001)
# inference
# loading the model which generated by training
model_dir = 'fluid_model/params_pass_2000.tar'
# Input multiple sets of data, Output the infer result in a array.
x = [ [-3], [13], [6], [7], [20] ]
print ("inference data : %s , expecting print : -2, 30, 16, 18, 44" % x)
infer_x = np.array(x).astype("float32")
inferencer = fluid.Inferencer(infer_func=inference_program, param_path=model_dir, place=place)
print "inference result :"
print inferencer.infer(inputs={'x': infer_x})
============================================= 运行时报错: 主要问题是: paddle.fluid.core.EnforceNotMet: Tensor holds the wrong type, it holds f at [/paddle/paddle/fluid/framework/tensor_impl.h:44] 尝试在如上程序中改动了1点,发现能绕过去 即 train_program 中 return [avg_cost, accuracy] 改为 return avg_cost ,运行程序就不报错了 请教一下是什么问题