tensorflow - keras :model.predict 返回形状错误的数组
问题描述
我对输出的形状有疑问model.predict
。
让我们考虑以下简单的虚拟模型:
import numpy as np
import pandas as pd
import tensorflow as tf
import string
from tensorflow.keras import layers
###Creating pseudo data
a = pd.DataFrame(np.random.randn(1000, 10), columns = [i for i in string.ascii_lowercase[:10]])
### Splitting data between train and test set
train = a.sample(frac=0.75, random_state=0)
test = a.drop(train.index)
### Creating features columns
f = []
for c in a.columns:
if c == 'j':
continue
x = tf.feature_column.numeric_column(c)
f.append(x)
l = layers.DenseFeatures(f)
### Creating model
model = tf.keras.models.Sequential()
model.add(l)
model.add(tf.keras.layers.Dense(
units = 64,
activation = 'relu',
name = 'hidden1'
)
)
model.add(tf.keras.layers.Dense(
units = 128,
activation = 'relu',
name = 'hidden2'
)
)
### Prepping training data for input in the model
features = {name : np.array(value) for name, value in train.items()}
label = np.array(features.pop('j'))
lr = 0.001
batch_size = 40
epochs = 40
model.compile(optimizer = tf.keras.optimizers.RMSprop(lr = lr),
loss = 'mean_squared_error',
metrics = [tf.keras.metrics.MeanSquaredError()])
model.fit(x=features, y=label, batch_size = batch_size, epochs = epochs, shuffle = True)
features_predict = {name : np.array(value) for name, value in test.items()}
label_predict = np.array(features_predict.pop('j'))
p = model.predict(x=features_predict)
现在如果我检查 p:
p.shape
它返回(250, 128)
(显然我希望预测j
值并保持形状(250,1)
我究竟做错了什么 ?
解决方案
模型的最后一层是具有 128 个单位的 Dense 层。它应该返回一个尺寸为 [batch_size, 128] 的张量。所以一切都如预期的那样。如果您希望输出具有每个样本的单个值,则应将单位数更改为 1。
推荐阅读
- javascript - 粒子 JS 的问题
- python - boto3 s3 api 在调用 GetBucketPolicyStatus 操作时失败并显示“(NoSuchBucketPolicy)”
- c# - 新插入的记录是否可用于同一事务中的后续 SQL 命令?
- autodesk-forge - 文件夹权限批量更新端点返回“访问被拒绝”错误
- c - 尝试扫描并打印结构中的字符串
- java - Swagger-Core 的对立面?
- spring-boot - 为什么我的 Spring Boot 单元测试不会在服务类中加载 @Value 属性?
- python - Python - 带有 STDIN 和 STDOUT 的子进程
- pine-script - 如何使用 Pine 脚本在监视列表中选择符号
- mongodb - 聚合管道中的可选中断