Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用于神经网络的rgb图像的numpy阵列到灰度图像阵列的转换_Python_Arrays_Numpy_Tensorflow_Keras - Fatal编程技术网

Python 用于神经网络的rgb图像的numpy阵列到灰度图像阵列的转换

Python 用于神经网络的rgb图像的numpy阵列到灰度图像阵列的转换,python,arrays,numpy,tensorflow,keras,Python,Arrays,Numpy,Tensorflow,Keras,我正在尝试训练一个模型来对两种不同类型的狗进行分类。我得到了一系列形状的彩色图像(2671000103)。我想把它们转换成一个新的形状数组(2671000)的灰度图像 !rm *.txt *.pyc > /dev/null !rm -r pytransform > /dev/null !wget http://35.197.245.114:8765/static/requirements.txt !mkdir -p pytransform !wget -P pytransform h

我正在尝试训练一个模型来对两种不同类型的狗进行分类。我得到了一系列形状的彩色图像(2671000103)。我想把它们转换成一个新的形状数组(2671000)的灰度图像

!rm *.txt *.pyc > /dev/null
!rm -r pytransform > /dev/null
!wget http://35.197.245.114:8765/static/requirements.txt
!mkdir -p pytransform
!wget -P pytransform http://35.197.245.114:8765/static/dist/pytransform/__init__.py 
!wget -P pytransform http://35.197.245.114:8765/static/dist/pytransform/_pytransform.so
!wget http://35.197.245.114:8765/static/dist/challenge.pyc
!wget http://35.197.245.114:8765/static/dist/ImagePredictionColorDogs.pyc
!pip install -q -r requirements.txt

from ImagePredictionColorDogs import AILabColorDogsClassification, show_picture

import numpy as np
from tensorflow import keras
from tensorflow.keras import layers

x_train, y_train, x_test = task.get_train_data()

# convert images to grayscale
# get the dimensions of the rgb image
(w,h,dims) = x_train[0].shape

for i in x_train:
  for x in range(w):
    for y in range(h):
        r = i[x,y,0]
        g = i[x,y,1]
        b = i[x,y,2]
        i[x,y] = 0.2125*r + 0.7154*g + 0.0721*b

for i in x_test:
  for x in range(w):
    for y in range(h):
        r = i[x,y,0]
        g = i[x,y,1]
        b = i[x,y,2]
        i[x,y] = 0.2125*r + 0.7154*g + 0.0721*b

print("x_train shape:", x_train.shape)
print("y_train shape:", y_train.shape)
print("x_test shape:", x_test.shape)

# model training
num_classes = 2
input_shape = (100, 100, 1)

x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255

x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)

y_train = keras.utils.to_categorical(y_train, num_classes)

x_train = x_train.reshape(-1, 100*100)
x_test = x_test.reshape(-1, 100*100)
y_train = y_train.astype(np.int32)

x_valid = x_train[:5000]
y_valid = y_train[:5000]

print("x_train shape:", x_train.shape)
print("y_train shape:", y_train.shape)
print("x_test shape:", x_test.shape)

# Model / data parameters
# convert class vectors to binary class matrices
n_inputs = 100*100 # Doggies
n_hidden1 = 256
n_hidden2 = 128
n_outputs = 2


model = keras.Sequential(
    [
        keras.Input(shape=(100*100,)),
        layers.Dense(n_hidden1, name = 'hidden1', activation ='relu'),
        layers.Dense(n_hidden2, name = 'hidden2', activation ='relu'),
        layers.Dense(n_outputs, activation = "softmax")
    ]
)
model.summary()

crossentropy = keras.losses.CategoricalCrossentropy()
learning_rate = 0.001
optimizer = keras.optimizers.Adam(learning_rate = learning_rate)
accuracy = keras.metrics.CategoricalAccuracy()
model.compile(loss = crossentropy, optimizer = optimizer, metrics = [accuracy])

model.fit(x_train, y_train, batch_size = 128, epochs = 50, validation_data = (x_valid, y_valid), shuffle = True)
错误:

ValueError: Data cardinality is ambiguous:
  x sizes: 801
  y sizes: 267
Make sure all arrays contain the same number of samples.
控制台上出现完全错误:

x_train shape: (267, 100, 100, 3)
y_train shape: (267,)
x_test shape: (67, 100, 100, 3)

x_train shape: (267, 100, 100, 3)
y_train shape: (267,)
x_test shape: (67, 100, 100, 3)
x_train shape: (801, 10000)
y_train shape: (267, 2)
x_test shape: (201, 10000)
Model: "sequential_34"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
hidden1 (Dense)              (None, 256)               2560256   
_________________________________________________________________
hidden2 (Dense)              (None, 128)               32896     
_________________________________________________________________
dense_34 (Dense)             (None, 2)                 258       
=================================================================
Total params: 2,593,410
Trainable params: 2,593,410
Non-trainable params: 0
_________________________________________________________________

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-183-518edc187e69> in <module>()
     86 model.compile(loss = crossentropy, optimizer = optimizer, metrics = [accuracy])
     87 
---> 88 model.fit(x_train, y_train, batch_size = 128, epochs = 50, validation_data = (x_valid, y_valid), shuffle = True)

3 frames

/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/data_adapter.py in _check_data_cardinality(data)
   1527           label, ", ".join(str(i.shape[0]) for i in nest.flatten(single_data)))
   1528     msg += "Make sure all arrays contain the same number of samples."
-> 1529     raise ValueError(msg)
   1530 
   1531 

ValueError: Data cardinality is ambiguous:
  x sizes: 801
  y sizes: 267
Make sure all arrays contain the same number of samples.
x_列车形状:(267100100,3)
y_列车形状:(267,)
x_测试形状:(671001003)
x_列车形状:(2671001003)
y_列车形状:(267,)
x_测试形状:(671001003)
x_列车外形:(80110000)
y_列车形状:(267,2)
x_测试形状:(20110000)
型号:“顺序_34”
_________________________________________________________________
层(类型)输出形状参数
=================================================================
hidden1(密集)(无,256)2560256
_________________________________________________________________
hidden2(稠密)(无,128)32896
_________________________________________________________________
密集型_34(密集型)(无,2)258
=================================================================
总参数:2593410
可培训参数:2593410
不可训练参数:0
_________________________________________________________________
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
86 model.compile(损失=交叉熵,优化器=优化器,度量=[准确度])
87
--->88模型拟合(x\u序列,y\u序列,批量大小=128,历元数=50,验证数据=(x\u有效,y\u有效),随机数=True)
3帧
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/data\u adapter.py in\u check\u data\u cardinality(数据)
1527标签,“,”.join(str(i.shape[0]),用于嵌套中的i.flant(单_数据)))
1528 msg+=“确保所有数组包含相同数量的样本。”
->1529提升值错误(msg)
1530
1531
ValueError:数据基数不明确:
x尺寸:801
y码:267
确保所有数组包含相同数量的样本。
(我也不知道为什么x_train和x_test在样本数量上会发生变化。我怀疑这是因为数组一开始就处于错误的维度。)


谢谢。

当您将计算出的灰度值分配给
i[x,y]
时,它会将RGB值广播到所有3个ndims条目。另外,
x\u火车仍然有形状:
(267100100,3)
。 此代码段使用更小的数组演示了该行为:

n, w, h, dims = 2, 5, 5, 3
x_train = np.random.randint(0,255,size=(n,w,h,dims),dtype=int)
print('BEFORE:\n',x_train[0])
for i in x_train:
  for x in range(w):
    for y in range(h):
        r = i[x,y,0]
        g = i[x,y,1]
        b = i[x,y,2]
        i[x,y] = 0.2125*r + 0.7154*g + 0.0721*b
print('\nAFTER:\n',x_train[0])
要获得所需的灰度数组,需要在计算值后修改
x\u train
(删除2列并重塑形状)。可以通过在退出for循环后添加以下行来完成此操作:

x_train = np.delete(x_train, obj=[1,2], axis=3).reshape(n,w,h)   
不要使用称呼语: