为什么预测工作没有拟合的模型在Keras

fivyi3re  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(167)

检查以下代码:

import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Flatten
from sklearn.model_selection import train_test_split

# Data
X = np.random.rand(1000, 100, 1)
y = np.random.randint(0, 2, (1000, 1))

# Splitting into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Conv1D
model = Sequential()
model.add(Conv1D(32, kernel_size=3, activation='relu', input_shape=(100, 1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())

# Predict before fitting the model
cnn_features_train = model.predict(X_train)
cnn_features_test = model.predict(X_test)

为什么它运行时没有抛出错误?.fit方法还没有稳定权重,它怎么能预测什么呢?
如果我尝试使用Sklearn做同样的事情(在拟合模型之前预测),我会得到预期误差,例如:

from sklearn.ensemble import RandomForestClassifier

# Data
X = np.random.rand(1000, 100, 1)
y = np.random.randint(0, 2, (1000, 1))

# Splitting into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Random Forest
rf = RandomForestClassifier()
rf.predict(X_test)

错误:

sklearn.exceptions.NotFittedError: This RandomForestClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
piwo6bdm

piwo6bdm1#

Keras不同于sklearn.predict ()无需调用.fit(),可帮助用户准备和调试Tensor的正确形状。

相关问题