- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我在 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'.
最佳答案
这是我的代码版本,它应该可以工作(用您的值填充 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/
如果您想使用 String.Concat() 连接 5 个或更多字符串,则它会使用 Concat(String[])。 为什么不一直使用 Concat(String[]) 而不再需要 Concat(S
今天在使用 String 时,我遇到了一种我以前不知道的行为。我无法理解内部发生的事情。 public String returnVal(){ return "5";
似乎在我所看到的任何地方,都有一些过时的版本,这些版本不再起作用。 我的问题似乎很简单。我有一个Java类,它映射到derby数据库。我正在使用注释,并且已经成功地在数据库中创建了所有其他表,但是在这
一、string::size_type() 在C++标准库类型 string ,在调用size函数求解string 对象时,返回值为size_type类型,一种类似于unsigned类型的int 数据
我正在尝试将数据保存到我的 plist 文件中,其中包含字符串数组的定义。我的plist - enter image description here 我将数据写入 plist 的代码是 -- let
我有一个带有键/值对的 JavaScript 对象,其中值是字符串数组: var errors = { "Message": ["Error #1", "Error #2"], "Em
例如,为了使用相同的函数迭代 List 和 List> ,我可以编写如下内容: import java.util.*; public class Test{ public static voi
第一个Dictionary就像 Dictionary ParentDict = new Dictionary(); ParentDict.Add("A_1", "1")
这是我的 jsp 文件: 我遇到了错误 The method replace(String, String, String) in the type Functions is not appl
我需要一些帮助。我有一个方法应该输出一个包含列表内容的 txt 文件(每行中的每个项目)。列表项是字符串数组。问题是,当我调用 string.Join 时,它返回文字字符串 "System.Strin
一位同事告诉我,使用以下方法: string url = "SomeURL"; string ext = "SomeExt"; string sub = "SomeSub"; string s
给定类: public class CategoryValuePair { String category; String value; } 还有一个方法: public
我正在尝试合并 Stream>>对象与所有 Streams 中的键一起映射到单个映射中. 例如, final Map someObject; final List>> list = someObjec
在这里使用 IDictionary 的值(value)是什么? 最佳答案 使用接口(interface)的值(value)始终相同:切换到另一个后端实现时,您不必更改客户端代码。 请考虑稍后分析您的代
我可以知道这两个字典声明之间的区别吗? var places = [String: String]() var places = [Dictionary()] 为什么当我尝试以这种方式附加声明时,只有
在 .NET 4.0 及更高版本中存在 string.IsNullOrWhiteSpace(string) 时,在检查字符串时使用 string.IsNullOrEmpty(string) 是否被视为
这个名字背后的原因是什么? SS64在 PowerShell 中解释此处的字符串如下: A here string is a single-quoted or double-quoted string
我打算离开 this 文章,尝试编写一个接受字符串和 &str 的函数,但我遇到了问题。我有以下功能: pub fn new(t_num: S) -> BigNum where S: Into {
我有一个结构为 [String: [String: String]] 的多维数组。我可以使用 for 循环到达 [String: String] 位,但我不知道如何访问主键(这个位 [String:
我正在尝试使用 sarama(管理员模式)创建主题。没有 ConfigEntries 工作正常。但我需要定义一些配置。 我设置了主题配置(这里发生了错误): tConfigs := map[s
我是一名优秀的程序员,十分优秀!