模型的特征数量必须与输入相匹配。模型 n_features 为 40,输入 n_features 为 38

Number of features of the model must match the input. Model n_features is 40 and input n_features is 38

我收到这个 error.please 给我任何解决问题的建议 it.here 是我的 code.i 我正在从 train.csv 获取训练数据并从另一个文件测试数据 test.csv.i 是机器学习的新手,所以我不明白 problem.give 我有什么建议。

import quandl,math    
import numpy as np    
import pandas as pd    
import matplotlib.pyplot as plt
from matplotlib import style
import datetime
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import metrics
train = pd.read_csv("train.csv", index_col=None)
test = pd.read_csv("test.csv", index_col=None)
vectorizer = CountVectorizer(min_df=1)
X1 = vectorizer.fit_transform(train['question'])
Y1 = vectorizer.fit_transform(test['testing'])
X=X1.toarray()
Y=Y1.toarray()
#print(Y.shape)
number=LabelEncoder()
train['answer']=number.fit_transform(train['answer'].astype('str'))
features = ['question','answer']
y = train['answer']
clf=RandomForestClassifier(n_estimators=100)
clf.fit(X[:25],y)
predicted_result=clf.predict(Y[17])
p_result=number.inverse_transform(predicted_result)
f = open('output.txt', 'w')
t=str(p_result)
f.write(t)
print(p_result)

您的代码存在多个问题。 但是与这个问题相关的是,你在训练数据和测试数据上都拟合了 CountVectorizer (vectorizer),这就是你获得不同特征的原因。

你应该做的是:

X1 = vectorizer.fit_transform(train['question'])

# The following line is changed
Y1 = vectorizer.transform(test['testing'])