- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个包含 n
行和 23
列(不包括索引)的 DataFrame。
首先,我将它们分成 X
和 Y
:
Y = df.pop("Target").values
X = df.values # now X has 22 columns
然后我使用train_test_split
来分割它们:
X_tr, X_val, y_tr, y_val = train_test_split(X, Y)
我将它们转换为数据集
:
dataset = tf.data.Dataset.from_tensor_slices((X_tr, y_tr))
dataset = dataset.batch(32)
valid_ds = tf.data.Dataset.from_tensor_slices((X_val, y_val))
问题是,当我创建模型时,我把input_shape
放错了,如下所示:
def create_model():
tfkl = tf.keras.layers
inp = tf.keras.Input(shape=(None, 22))
x = tfkl.Dense(128, activation="linear")(inp)
x = tfkl.Dense(64, activation="linear")(x)
x = tfkl.Dense(1, activation="linear")(x)
model = tf.keras.models.Model(inp, x)
model.compile(loss="mae", optimizer="adam", metrics=["mae"])
return model
当我运行 fit
时,在纪元结束时它会抛出错误:
ValueError: Input 0 of layer dense is incompatible with the layer: expected axis
-1 of input shape to have value 22 but received input with shape [22, 1]
我将其更改为 (None, None, 22)
和许多其他内容,但它不起作用。如有任何帮助,我们将不胜感激。
最佳答案
我能够复制您的问题。 X
有 1000
条记录和 22
特征,y
有 1
特征和 >1000
条记录。请引用下面的示例代码
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
X = np.random.random((1000,22))
y = np.random.random((1000,1))
X_train,X_test, y_train,y_test = train_test_split(X,y)
dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_data = dataset.shuffle(len(X_train)).batch(32)
train_data = train_data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
valid_ds = tf.data.Dataset.from_tensor_slices((X_test, y_test))
def create_model():
tfkl = tf.keras.layers
inp = tf.keras.Input(shape=(None,22))
x = tfkl.Dense(128, activation="linear")(inp)
x = tfkl.Dense(64, activation="linear")(x)
x = tfkl.Dense(1, activation="linear")(x)
model = tf.keras.models.Model(inp, x)
model.compile(loss="mae", optimizer="adam", metrics=["mae"])
return model
model=create_model()
model.summary()
model.fit(train_data, epochs=3, validation_data=valid_ds)
输出:
Model: "functional_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, None, 22)] 0
_________________________________________________________________
dense (Dense) (None, None, 128) 2944
_________________________________________________________________
dense_1 (Dense) (None, None, 64) 8256
_________________________________________________________________
dense_2 (Dense) (None, None, 1) 65
=================================================================
Total params: 11,265
Trainable params: 11,265
Non-trainable params: 0
_________________________________________________________________
Epoch 1/3
WARNING:tensorflow:Model was constructed with shape (None, None, 22) for input Tensor("input_1:0", shape=(None, None, 22), dtype=float32), but it was called on an input with incompatible shape (None, 22).
WARNING:tensorflow:Model was constructed with shape (None, None, 22) for input Tensor("input_1:0", shape=(None, None, 22), dtype=float32), but it was called on an input with incompatible shape (None, 22).
1/24 [>.............................] - ETA: 0s - loss: 0.3535 - mae: 0.3535WARNING:tensorflow:Model was constructed with shape (None, None, 22) for input Tensor("input_1:0", shape=(None, None, 22), dtype=float32), but it was called on an input with incompatible shape (22, 1).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-9499c98e2515> in <module>()
28 model.summary()
29
---> 30 model.fit(train_data, epochs=3, validation_data=valid_ds)
12 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
971 except Exception as e: # pylint:disable=broad-except
972 if hasattr(e, "ag_error_metadata"):
--> 973 raise e.ag_error_metadata.to_exception(e)
974 else:
975 raise
ValueError: in user code:
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1224 test_function *
return step_function(self, iterator)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1215 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
return fn(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1208 run_step **
outputs = model.test_step(data)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1174 test_step
y_pred = self(x, training=False)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:985 __call__
outputs = call_fn(inputs, *args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:386 call
inputs, training=training, mask=mask)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:508 _run_internal_graph
outputs = node.layer(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:976 __call__
self.name)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py:216 assert_input_compatibility
' but received input with shape ' + str(shape))
ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 22 but received input with shape [22, 1]
固定代码:
我已将输入形状从 (None, 22)
更改为 (22,)
和 验证数据
批量 32
为 valid_data = valid_ds.batch(32)
请引用如下所示的工作代码
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
X = np.random.random((1000,22))
y = np.random.random((1000,1))
X_train,X_test, y_train,y_test = train_test_split(X,y)
dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_data = dataset.shuffle(len(X_train)).batch(32)
train_data = train_data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
valid_ds = tf.data.Dataset.from_tensor_slices((X_test, y_test))
valid_data = valid_ds.batch(32)
def create_model():
tfkl = tf.keras.layers
inp = tf.keras.Input(shape=(22,))
x = tfkl.Dense(128, activation="linear")(inp)
x = tfkl.Dense(64, activation="linear")(x)
x = tfkl.Dense(1, activation="linear")(x)
model = tf.keras.models.Model(inp, x)
model.compile(loss="mae", optimizer="adam", metrics=["mae"])
return model
model=create_model()
model.summary()
model.fit(train_data, epochs=3, validation_data=valid_data)
输出:
Model: "functional_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 22)] 0
_________________________________________________________________
dense_3 (Dense) (None, 128) 2944
_________________________________________________________________
dense_4 (Dense) (None, 64) 8256
_________________________________________________________________
dense_5 (Dense) (None, 1) 65
=================================================================
Total params: 11,265
Trainable params: 11,265
Non-trainable params: 0
_________________________________________________________________
Epoch 1/3
24/24 [==============================] - 0s 4ms/step - loss: 0.2807 - mae: 0.2807 - val_loss: 0.2773 - val_mae: 0.2773
Epoch 2/3
24/24 [==============================] - 0s 2ms/step - loss: 0.2630 - mae: 0.2630 - val_loss: 0.2600 - val_mae: 0.2600
Epoch 3/3
24/24 [==============================] - 0s 2ms/step - loss: 0.2575 - mae: 0.2575 - val_loss: 0.2616 - val_mae: 0.2616
<tensorflow.python.keras.callbacks.History at 0x7ff6fb1ad358>
关于python - Pandas/Keras : use data from DataFrame to train Keras model, 输入形状错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64279017/
只是想知道这些结构之间有什么区别(text、data、rodata、bss 等)在链接描述文件中: .data : { *(.data) } .data : { *(.data*) }
Data 定义为其核心功能之一 gfoldl : gfoldl :: (Data a) => (forall d b. Data d => c (d -> b) -> d -> c b)
以下之间有什么区别:data-sly-use、data-sly-resource、data-sly-include 和 数据-sly-模板?我正在阅读 Sightly AEM 上的文档,我非常困惑。
我有一个 Spring Boot、Spring Data JPA (hibernate) Web 应用程序,并且想引入文本搜索功能。 我理解以下内容 hibernate search 或 spring
我不知道我的代码有什么问题。我读了其他有同样问题的人的一些问题,但没有找到答案。当我尝试编译时出现以下错误: ||In function 'main':| |35|error: expected ex
我不太确定为什么会收到此错误或其含义。我的数据框称为“数据”。 library(dplyr) data %>% filter(Info==1, Male==1) %>% lm(CFL_
我一直在 GitHub 等更现代的网站上看到这些属性,它们似乎总是与自定义的弹出窗口一致,如 title 属性。 Option 1 Option 2 Option 3 Option 4 我在 HTML
如何用 iCloud Core Data 替换我现有的 Core Data?这是我的持久商店协调员: lazy var persistentStoreCoordinator: NSPersistent
我一直在 GitHub 等更现代的网站上看到这些属性,它们似乎总是与自定义的弹出窗口一致,如 title 属性。 Option 1 Option 2 Option 3 Option 4 我在 HTML
我正在通过 this project 在 Android 上摆弄 node.js ,我需要一种方法将 js 文件部署到私有(private)目录(以隐藏源代码,防止用户篡改),该目录也物理存在于文件系
大家好我有点沮丧,所以我希望得到一些帮助。我的项目在 SwiftUI 中。我想使用图像选择器将图像保存到 Core Data。我实现了让 ImagePicker 工作,但我正在努力转换 Image -
我有以下数据和代码: mydf grp categ condition value 1 A X P 2 2 B X P 5
我一直在努力解决这个问题,但我根本找不到任何解决问题的方法。希望这里有人可以提供帮助。 我正在尝试为具有以下结构的某些数据创建个人选择矩阵: # A tibble: 2,152 x 32 a
我了解 Data.Map.Lazy 和 Data.Map.Strict 是不同的。但是,当您导入 Data.Map 时,您究竟导入了什么:严格的、惰性的还是两者的组合? 最佳答案 懒人。看着docs
我正在开发一个 C 程序,用于从 BerkeleyDB DBTree 数据库中提取数据值与特定模式匹配的记录。我创建数据库,打开它,将键的 DBT 和数据的另一个 DBT 清零,将 DBT 标志设置为
所以我有以下成员(member)历史表 User_ID | Start date | End Date | Type(0-7) | ---------------------------
随着最近推出的包dataframe ,我认为是时候正确地对各种数据结构进行基准测试,并突出每种数据结构的优势。我不是每个人的不同优势的专家,所以我的问题是,我们应该如何对它们进行基准测试。 我尝试过的
我有来自 API 的数据,但无法将数组中的数据设置为 vue.js 中的 this.data这是来自 API 的数据(JSON) 你能告诉我这个语法吗 {"id":1613, "name_org":"
在 Vue.js到目前为止,我已经找到了两种定义数据的方法:data: {} 和 data() { return; }. data: { defaultLayout: 'default' }
我正在研究Spring Data Rest Services,并在自定义拦截器中遇到一些问题。之前我使用spring-data-rest-webmvc 2.2.0并以以下方式添加了拦截器。 publi
我是一名优秀的程序员,十分优秀!