You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras/TensorFlow模型编译训练成功但预测时不兼容特征向量

问题:Model.predict()维度不匹配错误

我是TensorFlow和神经网络新手,正在构建一个回归问题的Sequential模型,输入层为接受(112,)维度的Normalization层,输出(24,)维度,中间包含若干Dense非线性层。模型已成功编译并完成训练(误差较高暂不考虑),但使用训练集中的样本调用model.predict()时出现错误:

Node: 'sequential/NonLin_1/Relu'
Matrix size-incompatible: In[0]: [1,32], In[1]: [112,512]
     [[{{node sequential/NonLin_1/Relu}}]] [Op:__inference_predict_function_6782]

模型摘要如下:

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 normalization (Normalizatio  (None, 112)              3         
 n)                                                              
                                                                 
 NonLin_1 (Dense)            (None, 512)               57856     
                                                                 
 NonLin_2 (Dense)            (None, 512)               262656    
                                                                 
 NonLin_3 (Dense)            (None, 512)               262656    
                                                                 
 Lin_Output (Dense)          (None, 24)                12312     
                                                                 
=================================================================
Total params: 595,483
Trainable params: 595,480
Non-trainable params: 3
_________________________________________________________________

完整代码:

import numpy as np
import tensorflow as tf
import csv

from tensorflow import keras
from tensorflow.keras import layers
from keras.models import Sequential
from keras.layers import Dense

### Read and Format Data
feat = 112 #number of features
outputs = 24 #number of outputs

with open('ForestPathExport.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    next(csv_reader)
    data = np.loadtxt(csv_file, delimiter=",")
    N = np.size(data, 0)  #determine number of samples
    xtrain = np.zeros((N,feat))
    ytrain = np.zeros((N,outputs))
    for i in range(N):
        xtrain[i,:] = data[i, 0:feat]
        ytrain[i,:] = data[i, feat:(feat+outputs)]

#print(np.shape(xtrain))
#(868, 112)
#print(np.shape(ytrain))
#(868, 24)
print('Data Import Complete')

### Build model
def model1(xtrain):

    normalizer = layers.Normalization(input_shape=[feat,], axis=None)
    normalizer.adapt(xtrain)

    # Build sequential model
    model = tf.keras.Sequential([normalizer,
                              layers.Dense(512, activation='relu', name='NonLin_1'),
                              layers.Dense(512, activation='relu', name='NonLin_2'),
                             layers.Dense(512, activation='relu', name='NonLin_3'),
                              layers.Dense(24, name='Lin_Output')])
    model.summary()

    model.compile(loss="mean_squared_error", optimizer="adam", metrics=["mean_squared_error"])
    return model

model = model1(xtrain)
history = model.fit(xtrain, ytrain, epochs=100, batch_size=190, validation_split=0.2)
xtest = xtrain[1,:]
#print(np.shape(xtest))
#(112,)
test_predict = model.predict(xtest)  #<-----Error

解决方案

问题根源在于输入数据的维度不匹配:

  • 模型训练时接收的是**(N, 112)**格式的批量数据(N为样本数)
  • xtest = xtrain[1,:]取出的是**(112,)的一维数组,而TensorFlow的predict()方法默认期望输入是二维批量数据**(形状为(样本数, 特征数))。当传入一维数组时,TensorFlow会错误地将其解释为「1个样本,32个特征」,与模型期望的112个特征冲突,导致矩阵乘法维度错误。

修复只需给xtest增加一个维度,将其转为**(1, 112)**的二维数组,有两种方式:

  1. 使用np.expand_dims():
xtest = np.expand_dims(xtrain[1,:], axis=0)
  1. 使用切片索引:
xtest = xtrain[1:2,:]

修改后再调用model.predict(xtest)即可正常运行。

内容的提问来源于stack exchange,提问作者T Bounds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:52:43