ValueError: Tensor Tensor(“conv2d_18/Relu:0“, shape=(?, 512, 512, 3), dtype=float32)

解决django+keras ValueError: Tensor Tensor(“conv2d_18/Relu:0”, shape=(?, 512, 512, 3), dtype=float32) is not an element of this graph.

报错信息
ValueError: Tensor Tensor("conv2d_18/Relu:0", shape=(?, 512, 512, 3), dtype=float32) is not an element of this graph.
排查问题
# 库版本
tensorflow==1.15
keras==2.3.1

# 尝试
在你create/load model 的地方之后加上代码:
self.graph = tf.get_default_graph()

在你使用model之前加上
with self.graph.as_default():
    (... do inference here ...)

# 继续报错
tensorflow.python.framework.errors_impl.FailedPreconditionError: 。。。from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exis

# 之后换了一种思路,如下

解决办法
pip install tensorflow==2.0

# 接着解决替换tensorflow2.0后产生的其他报错(相对简单)
# 之后django服务起来了
import torch import os import torch.nn as nn import torch.optim as optim import numpy as np import random import matplotlib.pyplot as plt class Net(nn.Module): def init(self): super(Net, self).init() self.conv1 = nn.Conv2d(1, 16, kernel_size=3,stride=1) self.pool = nn.MaxPool2d(kernel_size=2,stride=2) self.conv2 = nn.Conv2d(16, 32, kernel_size=3,stride=1) self.fc1 = nn.Linear(32 * 9 * 9, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 2) def forward(self, x): x = self.pool(nn.functional.relu(self.conv1(x))) x = self.pool(nn.functional.relu(self.conv2(x))) x = x.view(-1, 32 * 9 * 9) x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) folder_path1 = 'random_matrices2' # 创建空的tensor x = torch.empty((40, 1, 42, 42)) # 遍历文件夹内的文件,将每个矩阵转化为tensor并存储 for j in range(40): for j in range(40): file_name = 'matrix_{}.npy'.format(i) file_path1 = os.path.join(folder_path1, file_name) matrix1 = np.load(file_path1) x[j] = torch.from_numpy(matrix1).unsqueeze(0) folder_path2 = 'random_label2' y = torch.empty((40, )) for k in range(40): for k in range(40): file_name = 'label_{}.npy'.format(i) file_path2 = os.path.join(folder_path2, file_name) matrix2 = np.load(file_path2) y[k] = torch.from_numpy(matrix2) losses = [] for epoch in range(10): running_loss = 0.0 for i in range(40): inputs, labels = x[i], y[i] optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() losses.append(running_loss / 40) print('[%d] loss: %.3f' % (epoch + 1, running_loss / 40)) print('Finished Training') plt.plot(losses) plt.xlabel('Epoch') plt.ylabel('Loss') plt.show() 报错:ValueError: Expected input batch_size (1) to match target batch_size (0). 不改变y的形状,改变输出,怎么修改?
05-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值