问题描述 Issue Description
指南的模型开发入门的模型保存与载入,推荐使用paddle.jit.save/load(动态图),但是报错
Exception has occurred: ValueError
In transformed code:
File "XXXXXX.py", line 76, in forward
x = F.relu(x)
x = self.conv1(x)
~~~~~~~~~~~~~~~~~ <--- HERE
x = x + x1
x = F.relu(x)
这是代码原文,那个报错的HERE指的地方没有什么啊,
save
path = "H:/Desktop/XXX/XXX/evNet"
paddle.jit.save(
layer=layer,
path=path,
input_spec=[InputSpec(shape=[None, 15], dtype='float32')])
这是保存模型用的代码,也是直接从帮助里复制过来的
版本&环境信息 Version & Environment Information
Paddle version: 2.3.1
Paddle With CUDA: True
OS: Windows 10
Python version: 3.7.13
CUDA version: 11.2.152
Build cuda_11.2.r11.2/compiler.29618528_0
cuDNN version: None.None.None
Nvidia driver version: None
6条答案
按热度按时间c3frrgcw1#
麻烦贴下完整的报错和代码吧。
14ifxucb2#
好的,我正在用这个代码参加一个比赛,请不要发到公开平台上,多谢啦 下图是报错代码: 复制错误信息如下: Exception has occurred: ValueError In transformed code: File "h:\Desktop\pp\evaluationNet.py", line 76, in forward x = F.relu(x) x = self.conv1(x) ~~~~~~~~~~~~~~~~~ <--- HERE x = x + x1 x = F.relu(x) File "C:\ProgramData\Anaconda3\envs\paddle_env\lib\site-packages\paddle\fluid\dygraph\layers.py", line 930, in call return self._dygraph_call_func(inputs, kwargs) File "C:\ProgramData\Anaconda3\envs\paddle_env\lib\site-packages\paddle\fluid\dygraph\layers.py", line 915, in _dygraph_call_func outputs = self.forward(inputs, kwargs) File "C:\ProgramData\Anaconda3\envs\paddle_env\lib\site-packages\paddle\nn\layer\conv.py", line 347, in forward data_format=self._data_format) File "C:\ProgramData\Anaconda3\envs\paddle_env\lib\site-packages\paddle\nn\functional\conv.py", line 326, in conv1d format(x.shape)) ValueError: Input x should be 3D tensor, but received x with the shape of (-1, 32) File "C:\Users\congcong\AppData\Local\Temp\tmpy0tbyb73.py", line 13, in forward x = paddle.jit.dy2static.convert_call(self.conv1)(x) During handling of the above exception, another exception occurred: File "H:\Desktop\pp\evaluationNet.py", line 182, in <module> input_spec=[InputSpec(shape=[None, 15], dtype='float32')]) 完整代码如下: import paddle import paddle.nn.functional as F from paddle.io import Dataset from paddle.static import InputSpec #print(paddle.version) import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings("ignore") ev_path = 'H:/Desktop/pp/evaluation/Balance600.csv' ev = pd.read_csv(ev_path, index_col="FID") print(ev.head()) ''' fig, ax = plt.subplots() ev.plot(legend=False, ax=ax) plt.show() ''' data = np.array(ev) print(data) datay = data[:,0] #标签列 print(datay) data = (data - data.mean(axis=0))/data.std(axis=0) #Zscore标准化 #data = (data-data.min(axis=0))/(data.max(axis=0)-data.min(axis=0)) data[:,0] = datay print(data) train, test = train_test_split(data, test_size = 0.2,random_state=0,shuffle=True,stratify=datay) print(train) print(test) # define a dataset class MyDataset(Dataset): def init(self, data): self.data = paddle.to_tensor(data, dtype='float32') def getitem(self, idx): data = self.data[idx,1:] label = self.data[idx,0] return data, label def len(self): return len(self.data) train_dataset = MyDataset(train) valid_dataset = MyDataset(test) class MyNet(paddle.nn.Layer): def init(self, num_classes=1): super(MyNet, self).init() self.linear1 = paddle.nn.Linear(in_features=15, out_features=128) self.linear2 = paddle.nn.Linear(in_features=128, out_features=32) self.linear3 = paddle.nn.Linear(in_features=15, out_features=5) self.conv1 = paddle.nn.Conv1D(in_channels=32, out_channels=15, kernel_size=1,data_format='NLC') def forward(self, x): x1 = x x = self.linear1(x) x = F.relu(x) x = F.dropout(x,0.016) x = self.linear2(x) x = F.relu(x) x = self.conv1(x) x = x + x1 x = F.relu(x) x = F.dropout(x,0.001) x = self.linear3(x) return x # 参数设置 epoch_num = 100 batch_size = 138 learning_rate = 0.001 def train(model): print('训练开始') # 实例化模型 model = MyNet() # 将模型转换为训练模式 model.train() # 设置优化器,学习率,并且把模型参数给优化器 opt = paddle.optimizer.Adam(learning_rate=learning_rate,weight_decay=0.01,parameters=model.parameters()) # 设置损失函数 mse_loss = paddle.nn.MSELoss() # 设置数据读取器 train_loader = paddle.io.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) valid_loader = paddle.io.DataLoader(valid_dataset, batch_size=batch_size) val_acc_history = [] val_loss_history = [] for epoch in range(epoch_num): for batch_id, data in enumerate(train_loader()): #x = data[0].t() #矩阵转置 x = paddle.unsqueeze(data[0],-2) #print(type(x)) #print(x.shape) y = paddle.to_tensor(data[1],dtype='int64') #print(y.shape) logits = model(x) #print(logits.shape) #print(y.shape) loss = F.cross_entropy(logits, y, soft_label=False, axis=-1) if batch_id % 1000 == 0: print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, loss.numpy())) loss.backward() opt.step() opt.clear_grad() model.eval() accuracies = [] losses = [] for batch_id, data in enumerate(valid_loader()): x_data = paddle.unsqueeze(data[0],-2) y_data = paddle.to_tensor(data[1],dtype='int64') logits = model(x_data) loss = F.cross_entropy(logits, y_data) acc = paddle.metric.accuracy(logits, y_data) #accf = paddle.metric.accuracy() #acc = accf.compute(logits, y_data) accuracies.append(acc.numpy()) losses.append(loss.numpy()) #print("predict:") #print(logits) #print("trueLabel:") #print(y_data) avg_acc, avg_loss = np.mean(accuracies), np.mean(losses) print("[validation] accuracy/loss: {}/{}".format(avg_acc, avg_loss)) val_acc_history.append(avg_acc) val_loss_history.append(avg_loss) model.train() plt.plot(val_acc_history, label = 'validation accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.ylim([0.5, 0.8]) plt.legend(loc='lower right') plt.show() plt.plot(val_loss_history, label = 'validation loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.ylim([0.5, 2]) plt.legend(loc='lower right') plt.show() layer = MyNet() model = MyNet(num_classes=5) train(model) # save path = "H:/Desktop/pp/evaluation/evNet" paddle.jit.save( layer=layer, path=path, input_spec=[InputSpec(shape=[None, 15], dtype='float32')]) 钟凤媛 ***@. …
------------------ 原始邮件 ------------------ 发件人: "PaddlePaddle/Paddle" ***@***.***>; 发送时间: 2022年8月24日(星期三) 下午3:17 ***@***.***>; ***@***.******@***.***>; 主题: Re: [PaddlePaddle/Paddle] 动态图本地模型保存报错,Exception has occurred: ValueError In transformed code (Issue #45378) 麻烦贴下完整的报错和代码吧。 — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: ***@***.***>
gzszwxb43#
看下提示
ValueError: Input x should be 3D tensor, but received x with the shape of (-1, 32)
也麻烦格式化下代码和报错信息。
p1tboqfb4#
您好,辛苦您了,所报错的问题(ValueError: Input x should be 3D tensor, but received x with the shape of (-1, 32))正是令人困惑的地方,这个程序已经训练测试成功,并没有报错,只是加了save部分才有报错信息。我把运行过程做了断点,显示这一句输入张量为三维,shape为[138,1,32], 您请看运行截图如下: 下一步也设上断点,还是三维张量: 之前那个格式可能因为粘贴到mail里面有丢失,我把代码文件放在附件里面,请查收。 钟凤媛 @***. …
------------------ 原始邮件 ------------------ 发件人: "PaddlePaddle/Paddle" ***@***.***>; 发送时间: 2022年8月24日(星期三) 晚上7:21 ***@***.***>; ***@***.******@***.***>; 主题: Re: [PaddlePaddle/Paddle] 动态图本地模型保存报错,Exception has occurred: ValueError In transformed code (Issue #45378) 看下提示 ValueError: Input x should be 3D tensor, but received x with the shape of (-1, 32) 也麻烦格式化下代码和报错信息。 — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: ***@***.***>
8fq7wneg5#
check下inputspec中给的shape是否正确。应该就是shape的问题。
yvgpqqbh6#
非常感谢,正是shape设置的问题,仔细查看了函数的说明,发现了shape参数的详细要求,问题解决了。给你100个赞! 钟凤媛 @***. …
------------------ 原始邮件 ------------------ 发件人: "PaddlePaddle/Paddle" ***@***.***>; 发送时间: 2022年8月25日(星期四) 上午10:32 ***@***.***>; ***@***.******@***.***>; 主题: Re: [PaddlePaddle/Paddle] 动态图本地模型保存报错,Exception has occurred: ValueError In transformed code (Issue #45378) check下inputspec中给的shape是否正确。应该就是shape的问题。 — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: ***@***.***>