Python 重塑张量的正确方法是什么?

Python 重塑张量的正确方法是什么?,python,tensorflow,keras,scikit-image,Python,Tensorflow,Keras,Scikit Image,下面的代码是从胸部X光片进行肺部分割(2D)。它应该使用经过训练的模型“trained_model.hdf5”从胸部X光片生成肺面罩。在输入胸部x射线时,它应该能够识别哪些是肺,并相应地创建一个单独的肺面罩。trained_model.hdf5包含在JSRT数据集上训练的模型 #from load_data import loadDataJSRT, loadDataMontgomery import numpy as np import pandas as pd from keras.mode

下面的代码是从胸部X光片进行肺部分割(2D)。它应该使用经过训练的模型“trained_model.hdf5”从胸部X光片生成肺面罩。在输入胸部x射线时,它应该能够识别哪些是肺,并相应地创建一个单独的肺面罩。
trained_model.hdf5
包含在JSRT数据集上训练的模型

#from load_data import loadDataJSRT, loadDataMontgomery

import numpy as np
import pandas as pd
from keras.models import load_model
from skimage import morphology, io, color, exposure, img_as_float, transform
from keras.preprocessing.image import ImageDataGenerator

def loadDataGeneral(df, path, im_shape):
    X = []
    for i, item in df.iterrows():
        img = img_as_float(io.imread(path + str(item[0])))
        #mask = io.imread(path + item[1])
        img = transform.resize(img, im_shape)
        img = exposure.equalize_hist(img)
        img = np.expand_dims(img, -1)
        #mask = transform.resize(mask, im_shape)
        #mask = np.expand_dims(mask, -1)
        X.append(img)
        #y.append(mask)
    X = np.array(X)
    #y = np.array(y)
    X -= X.mean()
    X /= X.std()

    print( '### Dataset loaded')
    print( '\t{}'.format(path))
    #print( '\t{}\t{}'.format(X.shape, y.shape))
    #print( '\tX:{:.1f}-{:.1f}\ty:{:.1f}-{:.1f}\n'.format(X.min(), X.max(), y.min(), y.max()))
    print( '\tX.mean = {}, X.std = {}'.format(X.mean(), X.std()))
    return X



if __name__ == '__main__':

    # Path to csv-file. File should contain X-ray filenames as first column,
    # mask filenames as second column.
    csv_path = 'idx.csv'
    # Path to the folder with images. Images will be read from path + path_from_csv
    path = 'Data/'

    df = pd.read_csv(csv_path)

    # Load test data
    im_shape = (256, 256)
    X = loadDataGeneral(df, path, im_shape)
    #print('***X= ',X)
    n_test = X.shape[0]
    inp_shape = X[0].shape

    # Load model
    model_name = 'trained_model.hdf5'
    UNet = load_model(model_name)

    # For inference standard keras ImageGenerator is used.
    test_gen = ImageDataGenerator(rescale=1.)

    ious = np.zeros(n_test)
    dices = np.zeros(n_test)

    i = 0

    print("TEST_GEN ",test_gen)

    print(len(X))
    for xx in test_gen.flow(X, batch_size=1):
        xx = xx[0:4]
        img = exposure.rescale_intensity(np.squeeze(xx), out_range=(0,1))
        pred = UNet.predict(xx)[..., 0].reshape(inp_shape[:2])
        #mask = yy[..., 0].reshape(inp_shape[:2])

        # Binarize masks
        #gt = mask > 0.5
        pr = pred > 0.5

        # Remove regions smaller than 2% of the image
        pr = remove_small_regions(pr, 0.02 * np.prod(im_shape))

        io.imsave('results/{}'.format(df.iloc[i][0]), masked(img, pr, 1))

        #ious[i] = IoU(gt, pr)
        #dices[i] = Dice(gt, pr)
        #print(df.iloc[i][0], ious[i], dices[i])

        i += 1
        if i == n_test:
            break
但是我得到了这个错误:

### Dataset loaded
        Data/
        X.mean = -1.042684457293793e-15, X.std = 1.0000000000000002
2018-09-28 09:45:55.598419: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-09-28 09:45:55.605772: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
C:\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\saving.py:304: UserWarning: Error in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer.
  warnings.warn('Error in loading the saved optimizer '
TEST_GEN  <keras_preprocessing.image.ImageDataGenerator object at 0x00000159CC91AEB8>
5
Traceback (most recent call last):
  File "inference_1.py", line 67, in <module>
    for xx in test_gen.flow(X, batch_size=1):
  File "C:\Anaconda3\envs\tensorflow\lib\site-packages\keras_preprocessing\image.py", line 867, in flow
    subset=subset)
  File "C:\Anaconda3\envs\tensorflow\lib\site-packages\keras_preprocessing\image.py", line 1427, in __init__
    'with shape', self.x.shape)
ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (5, 256, 256, 3, 1))
加载的数据集 资料/ X.mean=-1.042684457293793e-15,X.std=1.0000000000000002 2018-09-28 09:45:55.598419:wc:\tf\u jenkins\home\workspace\rel win\M\windows\PY\36\tensorflow\core\platform\cpu\u feature\u guard.cc:45]tensorflow库的编译不是为了使用AVX指令,但这些指令在您的机器上可用,可以加快cpu计算。 2018-09-28 09:45:55.605772:wc:\tf\u jenkins\home\workspace\rel win\M\windows\PY\36\tensorflow\core\platform\cpu\u feature\u guard.cc:45]tensorflow库的编译不是为了使用AVX2指令,但这些指令在您的机器上可用,可以加快cpu计算。 C:\Anaconda3\envs\tensorflow\lib\site packages\keras\engine\saving.py:304:UserWarning:加载保存的优化器状态时出错。因此,您的模型从一个新初始化的优化器开始。 warnings.warn('加载保存的优化器时出错' 测试发电机 5. 回溯(最近一次呼叫最后一次): 文件“推理_1.py”,第67行,在 对于测试生成流中的xx(X,批次尺寸=1): 文件“C:\Anaconda3\envs\tensorflow\lib\site packages\keras\u preprocessing\image.py”,第867行,在flow中 子集=子集) 文件“C:\Anaconda3\envs\tensorflow\lib\site packages\keras\u preprocessing\image.py”,第1427行,在\uu init中__ “带形状”,self.x.shape) ValueError:('NumpyArrayIterator'中的输入数据应具有秩4。您传递了一个具有形状的数组',(5,256,256,3,1))
如何重塑张量?我做错了什么

ImageDataGenerator
希望输入的形状为
(样本、高度、宽度、通道)
,但在您的情况下,还有一个额外的维度。但是您输入的
X
的形状是
(示例、高度、宽度、通道,1)
,因此您需要先删除最后一个维度

要回答你关于重塑张量的问题,有多种方法。 试一试

X=X[:,:,:,0]

X=X[:,:,:,-1]


X=tf.重塑(X,[5256256,3])
ImageDataGenerator
希望输入的形状为
(样本、高度、宽度、通道)
,但在您的情况下,有一个额外的尺寸。但是您输入的
X
的形状是
(示例、高度、宽度、通道,1)
,因此您需要先删除最后一个维度

要回答你关于重塑张量的问题,有多种方法。 试一试

X=X[:,:,:,0]

X=X[:,:,:,-1]

X=tf.重塑(X[5256256,3])