检查以下代码:
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.
1条答案
按热度按时间piwo6bdm1#
Keras不同于
sklearn
,.predict ()
无需调用.fit()
,可帮助用户准备和调试Tensor的正确形状。