xlearn的预测函数给出的mse与您自己查看预测并计算得到的mse不同。以下是执行此操作的代码;您可以通过克隆xlearn仓库并将下面的代码复制到仓库中的demo/regression/house_price
来运行它
# Copyright (c) 2018 by contributors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import xlearn as xl import pandas as pd from sklearn.metrics import mean_squared_error # Training task # param: # 0. regression task # 1. learning rate: 0.2 # 2. regular lambda: 0.002 # 3. evaluation metric: mae fm_model = xl.create_linear() # Use factorization machine fm_model.setTrain("./house_price_train.txt") # Training data fm_model.setValidate("./house_price_test.txt") # Validation data fm_model.disableNorm() # fm_model.setSigmoid() # fm_model.disableEarlyStop() param = {'task':'reg', 'lr':0.0002, 'lambda':0.00001, 'metric':'rmse', 'epoch':100} # Start to train # The trained model will be stored in model.out print("here") fm_model.fit(param, './model.out') fm_model.setTest("./house_price_test.txt") # Test data # Prediction task # Start to predict # The output result will be stored in output.txt outs = fm_model.predict("./model.out", "./output.txt") true = pd.read_csv("./house_price_test.txt", sep='\t', header=None)[0] # print(true) preds = pd.read_csv("./output.txt", header=None)[0] # Calculate using sklearn print(mean_squared_error(true, preds)) # Self calculate sq = 0.0 for t, p in zip(true, preds): sq += (t - p) ** 2 print(sq/len(true))
如果您将其保存为min_eg.py,只需在安装xlearn后运行python min_eg.py
即可。
您将得到以下输出:
有趣的是,您得到的MSE总是预测函数报告的mse的两倍。
任何帮助都将不胜感激;我想知道其他人是否也遇到了同样的问题。
回答:
很多人使用1/2 MSE作为损失函数,因为这使得导数计算更加“简单”。鉴于他们使用“损失”这个词而不是“MSE”或其他类似的词,我猜这就是发生的情况。
为了清楚起见,如果您的损失函数是
1/2n * [(y_1 – p_1)^2 + … + (y_n – p_n)^2]
那么相对于p的导数将是
-1/n * [(y_1 – p_1) + … + (y_n – p_n)]
因为使用幂法则时会乘以2,所以2会消失。
抱歉格式不好…我不知道这里如何做数学公式。