gpt4 book ai didi

numpy - Keras(Numpy 输入)TypeError : Error converting shape to a TensorShape: int() argument must be a string, 类字节对象或数字,而不是 'tuple'

转载 作者:行者123 更新时间:2023-12-04 15:54:27 28 4
gpt4 key购买 nike

您好,我在 Keras 中遇到错误。

输入是一个维度为 (90, 7225) 的 numpy 数组

print(np_ip.shape)  ## (90, 7225)
print(np_ip)
(90, 7225)
[['0' '1' '0' ... '0' '0' '0']
['1' '0' '0' ... '0' '0' '0']
['1' '0' '0' ... '0' '0' '0']
...
['0' '0' '1' ... '0' '0' '0']
['1' '0' '0' ... '0' '0' '0']
['1' '0' '0' ... '0' '0' '0']]

我已将 7225 维序列 reshape 为 85*85 维二维 numpy 数组。

np1 = (np_ip).reshape(90,85,85) ## 90 examples of 85*85 each
print(np1.shape) ## (90, 85, 85)
print(np1[0])
(90, 85, 85)
[['0' '1' '0' ... '0' '1' '0']
['0' '1' '0' ... '0' '1' '0']
['0' '0' '0' ... '0' '0' '0']
...
['0' '0' '0' ... '0' '0' '0']
['0' '0' '0' ... '0' '0' '0']
['0' '0' '0' ... '0' '0' '0']]

现在,在 reshape 输入后,现在输入到 Keras 的 Conv Nw。

import numpy as np
import keras
from keras import backend as k
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
from keras.models import Sequential
from keras.layers import *
from keras import backend as K

print(np_ip.shape) ## (90, 7225)
print(np1.shape) ## (90, 85, 85)

#np_ip = np.expand_dims(np_ip, axis=1)

X_train = np1[:65]
Y_train = dataframe.label[:65]
Y_train = Y_train.values.reshape((65,1))

X_test = np1[65:85]
Y_test = dataframe.label[65:85]
Y_test = Y_test.values.reshape((20,1))

X_pred = np1[86:]
Y_pred = dataframe.label[86:]
Y_pred = Y_pred.values.reshape((4,1))

print(np1.shape) ## (90, 85, 85)
model = Sequential([
Conv2D(32, (3, 3), strides=(1, 1), activation = 'relu',
padding = 'valid', input_shape = (1, np1.shape), name = 'lyr_1'), #(65, 1779, 4, 1)),
Conv2D(32, (5, 5), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_2'),
Conv2D(32, (5, 5), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_3'),
Conv2D(32, (3, 3), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_4'),
Flatten(),
Dense(100, activation = 'relu', name='dense_lyr'),
Dense(50, activation = 'relu'),
Dense(2, activation = 'softmax') # The error indicates that problem is in this line of code
])

model.compile(Adam(lr = 0.0001), loss = 'categorical_crossentropy', metrics = ['accuracy'])

model.fit(X_train, Y_train, validation_data = 0.1, epochs = 10, verbose = 2)

(90, 85, 85)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in make_shape(v, arg_name)
140 try:
--> 141 shape = tensor_shape.as_shape(v)
142 except TypeError as e:

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\framework\tensor_shape.py in as_shape(shape)
945 else:
--> 946 return TensorShape(shape)
947

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\framework\tensor_shape.py in __init__(self, dims)
540 # Got a list of dimensions
--> 541 self._dims = [as_dimension(d) for d in dims_iter]
542 self._ndims = None

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\framework\tensor_shape.py in <listcomp>(.0)
540 # Got a list of dimensions
--> 541 self._dims = [as_dimension(d) for d in dims_iter]
542 self._ndims = None

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\framework\tensor_shape.py in as_dimension(value)
481 else:
--> 482 return Dimension(value)
483

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\framework\tensor_shape.py in __init__(self, value)
36 else:
---> 37 self._value = int(value)
38 if (not isinstance(value, compat.bytes_or_text_types) and

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

抱歉打扰了,但这里的错误指出 Dense(2, activation = 'softmax') 的输入有问题,我无法理解为什么? (上面和下面block中的错误属于同一个错误,我在这里分解以引起您的注意)

    During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
<ipython-input-22-3c8061ff42fc> in <module>()
8 Dense(100, activation = 'relu', name='dense_lyr'),
9 Dense(50, activation = 'relu'),
---> 10 Dense(2, activation = 'softmax')
11 ])
12

D:\Installed_Programs\anaconda3\lib\site-packages\keras\models.py in __init__(self, layers, name)
399 if layers:
400 for layer in layers:
--> 401 self.add(layer)
402
403 def add(self, layer):

D:\Installed_Programs\anaconda3\lib\site-packages\keras\models.py in add(self, layer)
430 # Instantiate the input layer.
431 x = Input(batch_shape=layer.batch_input_shape,
--> 432 dtype=layer.dtype, name=layer.name + '_input')
433 # This will build the current layer
434 # and create the node connecting the current layer

D:\Installed_Programs\anaconda3\lib\site-packages\keras\engine\topology.py in Input(shape, batch_shape, name, dtype, sparse, tensor)
1424 name=name, dtype=dtype,
1425 sparse=sparse,
-> 1426 input_tensor=tensor)
1427 # Return tensor including _keras_shape and _keras_history.
1428 # Note that in this case train_output and test_output are the same pointer.

D:\Installed_Programs\anaconda3\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
85 warnings.warn('Update your `' + object_name +
86 '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87 return func(*args, **kwargs)
88 wrapper._original_function = func
89 return wrapper

D:\Installed_Programs\anaconda3\lib\site-packages\keras\engine\topology.py in __init__(self, input_shape, batch_size, batch_input_shape, dtype, input_tensor, sparse, name)
1335 dtype=dtype,
1336 sparse=self.sparse,
-> 1337 name=self.name)
1338 else:
1339 self.is_placeholder = False

D:\Installed_Programs\anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py in placeholder(shape, ndim, dtype, sparse, name)
430 x = tf.sparse_placeholder(dtype, shape=shape, name=name)
431 else:
--> 432 x = tf.placeholder(dtype, shape=shape, name=name)
433 x._keras_shape = shape
434 x._uses_learning_phase = False

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in placeholder(dtype, shape, name)
1732 "eager execution.")
1733
-> 1734 return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
1735
1736

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py in placeholder(dtype, shape, name)
5923 if shape is None:
5924 shape = None
-> 5925 shape = _execute.make_shape(shape, "shape")
5926 _, _, _op = _op_def_lib._apply_op_helper(
5927 "Placeholder", dtype=dtype, shape=shape, name=name)

D:\Installed_Programs\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in make_shape(v, arg_name)
141 shape = tensor_shape.as_shape(v)
142 except TypeError as e:
--> 143 raise TypeError("Error converting %s to a TensorShape: %s." % (arg_name, e))
144 except ValueError as e:
145 raise ValueError("Error converting %s to a TensorShape: %s." % (arg_name,

TypeError: Error converting shape to a TensorShape: int() argument must be a string, a bytes-like object or a number, not 'tuple'.

最佳答案

  • 您需要在 np1 中添加过滤器维度。
  • 应根据 binary_crossentropy 更改 categorical_crossentropy
  • 替换 validation_split 上的 validation_data。

这是我的代码版本,它应该可以工作(用您的值填充 X、Y 数组):

np1 = (np_ip).reshape(90,85,85, 1)

X_train = np1[:65]
Y_train = np.zeros((65, 1))

X_test = np1[65:85]
Y_test = np.zeros((20, 1))

X_pred = np1[86:]
Y_pred = np.zeros((4, 1))

print(np1.shape) ## (90, 85, 85)
model = Sequential([
Conv2D(32, (3, 3), strides=(1, 1), activation = 'relu',
padding = 'valid', input_shape = np1.shape[1:], name = 'lyr_1'), #(65, 1779, 4, 1)),
Conv2D(32, (5, 5), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_2'),
Conv2D(32, (5, 5), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_3'),
Conv2D(32, (3, 3), strides=(1, 1), activation = 'relu', padding= 'valid', name = 'lyr_4'),
Flatten(),
Dense(100, activation = 'relu', name='dense_lyr'),
Dense(50, activation = 'relu'),
Dense(1, activation = 'sigmoid') # The error indicates that problem is in this line of code
])

model.compile(Adam(lr = 0.0001), loss = 'binary_crossentropy', metrics = ['accuracy'])

model.fit(X_train, Y_train, validation_split=0.1, epochs = 10, verbose = 2)

关于numpy - Keras(Numpy 输入)TypeError : Error converting shape to a TensorShape: int() argument must be a string, 类字节对象或数字,而不是 'tuple',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351255/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com