PYcharm报错invalid type

import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split
#定义预处理后的图片(我的和别人的)所在目录如下。
my_face_path = r'D:\data\my_faces'
other_faces_path = r'D:\data\other_faces'
size = 64
#调整或规范图片大小。
imgs = []
labs = []

#重新创建图形变量
tf.compat.v1.reset_default_graph()
#获取需要填充的图片大小


def getPaddingSize(img1):
    h, w, _ = img1.shape
    top, bottom, left, right = (0, 0, 0, 0)
    longest = max(h, w)

    if w < longest:
        tmp = longest - w
        #//表示整除符号
        left = tmp // 2
        right = tmp - left
    elif h < longest:
        tmp = longest - h
        top = tmp // 2
        bottom = tmp - top
    else:
        pass
    return top, bottom, left, right


tf.compat.v1.disable_eager_execution()


#读取测试图片
def readData(path, h=size, w=size):
    for filename in os.listdir(path):
        if filename.endswith('.jpg'):
            filename = path + '/' + filename

            img = cv2.imread(filename)

            top, bottom, left, right = getPaddingSize(img)
            #将图片放大,扩充边缘部分
            img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])
            img = cv2.resize(img, (h, w))

            imgs.append(img)
            labs.append(path)


readData(my_face_path)
readData(other_faces_path)
#将图片数据与标签转换成数组
imgs = np.array(imgs)
labs = np.array([[0, 1] if lab == my_face_path else [1, 0] for lab in labs])
#随即划分测试集与训练集
train_x, test_x, train_y, test_y = train_test_split(imgs, labs, test_size=0.05, random_state=random.randint(0, 100))
#参数:图片数据的总数,图片的高,宽,通道
train_x = train_x.reshape(train_x.shape[0], size, size, 3)
test_x = test_x.reshape(test_x.shape[0], size, size, 3)
#将数据转换成小于1的数
train_x = train_x.astype('float32')/255.0
test_x = test_x.astype('float32')/255.0

print('train size:%s, test size:%s' % (len(train_x), len(test_x)))


#图片块,每次取100张图片
batch_size = 20
num_batch = len(train_x) // batch_size

#定义变量及神经网络层
x = tf.compat.v1.placeholder(tf.float32, [None, size, size, 3])
y_ = tf.compat.v1.placeholder(tf.float32, [None, 2])

keep_prob_5 = tf.compat.v1.placeholder(tf.float32)
keep_prob_75 = tf.compat.v1.placeholder(tf.float32)


def weightVariable(shape):
    init = tf.compat.v1.random_normal(shape, stddev=0.01)
    return tf.Variable(init)


def biasVariable(shape):
    init = tf.compat.v1.random_normal(shape)
    return tf.Variable(init)


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 2, 2, 1], padding='SAME')


def maxPool(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='SAME')


def dropout(x, keep):
    return tf.nn.dropout(x, keep)


#定义卷积神经网络框架
def cnnLayer():
    #第一层
    W1 = weightVariable([3, 3, 3, 32])   #卷积核大小(3,3), 输入通道(3), 输出通道(32)
    b1 = biasVariable([32])
    #卷积
    conv1 = tf.nn.relu(conv2d(x, W1)+b1)
    #池化
    pool1 = maxPool(conv1)
    #减少过拟合,随即让某些权重不更新
    drop1 = dropout(pool1, keep_prob_5)

    #第二层
    W2 = weightVariable([3, 3, 32, 64])
    b2 = biasVariable([64])
    conv2 = tf.nn.relu(conv2d(drop1, W2) + b2)
    pool2 = maxPool(conv2)
    drop2 = dropout(pool2, keep_prob_5)

    #第三层
    W3 = weightVariable([3, 3, 64, 64])
    b3 = biasVariable([64])
    conv3 = tf.nn.relu(conv2d(drop2, W3) + b3)
    pool3 = maxPool(conv3)
    drop3 = dropout(pool3, keep_prob_5)

    #全连接层
    Wf = weightVariable([8*16*32, 512])
    bf = biasVariable([512])
    drop3_flat = tf.reshape(drop3, [-1, 8*16*32])
    dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)
    dropf = dropout(dense, keep_prob_75)

    #输出层
    Wout = weightVariable([512, 2])
    bout = weightVariable([2])
    #out = tf.matmul(dropf.Wout) + bout
    out = tf.add(tf.matmul(dropf, Wout), bout)
    return out

#训练模型


def cnnTrain():
    out = cnnLayer()

    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_))

    train_step = tf.compat.v1.train.AdamOptimizer(0.01).minimize(cross_entropy)
    # 比较标签是否相等,再求所有数的平均值,tf。cast(强制转换类型)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y_, 1)), tf.float32))
    # 将loss与accuracy保存以供tensorboard使用
    tf.summary.scalar('loss', cross_entropy)
    tf.summary.scalar('accuracy', accuracy)
    merged_summary_op = tf.compat.v1.summary.merge_all()
    # 数据保存期的初始化
    saver = tf.compat.v1.train.Saver()

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())

        summary_writer = tf.compat.v1.summary.FileWriter('.tmp', graph=tf.compat.v1.get_default_graph())
        for n in range(10):
            #每次取128(batch_size)张图片
            for i in range(num_batch):
                batch_x = train_x[i*batch_size: (i+1)*batch_size]
                batch_y = train_y[i*batch_size: (i+1)*batch_size]
                # 开始训练数据,同时训练3个变量,返回3个数据
                _, loss, summary = sess.run([train_step, cross_entropy, merged_summary_op],
                                            feed_dict={x: batch_x, y_: batch_y, keep_prob_5: 0.5, keep_prob_75: 0.75})
                summary_writer.add_summary(summary, n*num_batch+i)
                #打印损失
                print(n*num_batch+i, loss)

                if(n*num_batch+i) % 40 == 0:
                    #获取测试数据的准确率
                    acc = accuracy.eval({x: test_x, y_: test_y, keep_prob_5: 1.0, keep_prob_75: 1.0})
                    print(n*num_batch+i, acc)
                    #由于数据不多,这里设为准确率大于0.80时保存并输出
                    if acc > 0.8 and n > 2:
                        saver.save(sess, r'F:\data')
                        #sys.exit(0)
        #print('accuracy less 0.80, exited')
cnnTrain()

求问 所有的值之间的逻辑都没有问题 为什么fetch不到有效的r% 求问

以下是报错内容

2021-04-04 19:40:44.269590: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "D:/python PROJRCT/cut test face2.py", line 195, in <module>
    cnnTrain()
  File "D:/python PROJRCT/cut test face2.py", line 180, in cnnTrain
    _, loss, summary = sess.run([train_step, cross_entropy, merged_summary_op],
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 957, in run
    result = self._run(None, fetches, feed_dict, options_ptr,
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 1165, in _run
    fetch_handler = _FetchHandler(
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 477, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 266, in for_fetch
    return _ListFetchMapper(fetch)
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 378, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 378, in <listcomp>
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "D:\ANACONDA\lib\site-packages\tensorflow\python\client\session.py", line 262, in for_fetch
    raise TypeError('Fetch argument %r has invalid type %r' %
TypeError: Fetch argument None has invalid type <class 'NoneType'>

 

 

检查一下Fetch argument类型是不是有问题

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632