我正在尝试将Softmax与TensorFlow结合使用,但得到了一个值E

2024-06-10 01:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

def Convolution(img):
    kernel = tf.Variable(tf.truncated_normal(shape=[180, 180, 3, 3], stddev=0.1))
    img = img.astype('float32')
    img = tf.nn.conv2d(np.expand_dims(img, 0), kernel, strides=[ 1, 15, 15, 1], padding='VALID')  # + Bias1
    return img
def Max_Pool(img):
    img = tf.nn.max_pool(img, ksize=[1,2,2,1] , strides=[1,2,2,1], padding='VALID')
    return img

GmdMiss_Folder = os.path.join(os.getcwd(), '..', 'Photo', 'GMD Miss')
GmdMiss_List = os.listdir(GmdMiss_Folder)

GMD_Miss_Y = [0,0,1]
GMD_Miss_Y = np.tile(GMD_Miss_Y, (len(GmdMiss_List), 1))
Img_Miss_List = []

for i in range(0, len(GmdMiss_List)):
    print(i)
    Img = os.path.join(os.getcwd(), GmdMiss_Folder, GmdMiss_List[i])
    Img = cv2.imread(Img)
    Img = cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)
    Img = np.array(Img)
    Img = cv2.resize(Img, dsize=(1920, 1080), interpolation=cv2.INTER_AREA)
    Img_Miss_List.append(Img)
i = 0
while True:
    print(i)
    Img = Img_Miss_List[i]
    print(Img)
    print(Img)
    with tf.Session() as sess:
        graph = tf.Graph()
        with graph.as_default():
            with tf.name_scope("Convolution"):
                Img = Convolution(Img)
            with tf.name_scope("Relu_Function"):
                Img = tf.nn.relu(Img)
            with tf.name_scope("MaxPool"):
                Img = Max_Pool(Img)
                print(Img.shape)
            with tf.name_scope("Img_Fatten"):
                Img_Flatten = tf.reshape(Img, [-1, 30*58*3])
            with tf.name_scope("Fully_Connected"):
                X = Img_Flatten    # img is X
            with tf.name_scope("Output_layer"):
                Y = tf.placeholder(tf.float32, shape=[None, 3])
                W = tf.Variable(tf.zeros(shape=[30*58*3, 3]))
                B = tf.Variable(tf.zeros(shape=[3]))

                with tf.name_scope("Logits"):
                    Logits = tf.matmul(Img_Flatten, W) + B
                with tf.name_scope("SoftMax"):
                    Y_Pred = tf.nn.softmax(Logits)

请注意,下面问题中的代码也包含在上面的While语句中

with tf.name_scope("Learning"):
    with tf.name_scope("Reduce_Mean"):
        Loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=Logits, labels=GMD_Miss_Y))

错误是

ValueError: Cannot reshape a tensor with 3 elements to shape [1] (1 elements) for 'Learning/Reduce_Mean/softmax_cross_entropy_with_logits/Reshape_2' (op: 'Reshape') with input shapes: [3], [1] and with input tensors computed as partial shapes: input[1] = [1].


Tags: nameimgostfwithnncv2list