缩放数据时,为什么训练数据集使用’fit’和’transform’,而测试数据集只使用’transform’?
SAMPLE_COUNT = 5000
TEST_COUNT = 20000
seed(0)
sample = list()
test_sample = list()
for index, line in enumerate(open('covtype.data','rb')):
if index < SAMPLE_COUNT:
sample.append(line)
else:
r = randint(0,index)
if r < SAMPLE_COUNT:
sample[r] = line
else:
k = randint(0,index)
if k < TEST_COUNT:
if len(test_sample) < TEST_COUNT:
test_sample.append(line)
else:
test_sample[k] = line
from sklearn.preprocessing import StandardScaler
for n, line in enumerate(sample):
sample[n] = map(float, line.strip().split(','))
y = np.array(sample)[:,-1]
scaling = StandardScaler()
X = scaling.fit_transform(np.array(sample)[:,:-1]) ##here use fit and transform
for n,line in enumerate(test_sample):
test_sample[n] = map(float,line.strip().split(','))
yt = np.array(test_sample)[:,-1]
Xt = scaling.transform(np.array(test_sample)[:,:-1])##why here only use transform
正如注释所说,为什么Xt只用transform而不用fit?
原文由 littlely 发布,翻译遵循 CC BY-SA 4.0 许可协议
我们在训练数据上使用
fit_transform()
以便我们学习训练数据缩放的参数,同时我们缩放训练数据。我们只在测试数据上使用transform()
因为我们使用在训练数据上学习的缩放参数来缩放测试数据。这是缩放的标准程序。你总是在火车上学习你的缩放参数,然后在测试中使用它们。这是一篇很好地解释它的文章: https ://sebastianraschka.com/faq/docs/scale-training-test.html