所以我想在keras之后计算R2 = 1 - residual_ss/y_ss
。我使用预测model.predict()
来计算residual_ss
。但是,residual_ss
比y_ss
大得多,这导致负R2
。由于residual_ss = n*mse
和mse
也是损失函数,因此代码在模型之后显示了mse
的计算结果:
import keras
keras.__version__
from keras.datasets import boston_housing
import pandas as pd
import numpy as np
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
test_data -= mean
test_data /= std
from keras import models
from keras import layers
def build_model():
# Because we will need to instantiate
# the same model multiple times,
# we use a function to construct it.
model = models.Sequential()
model.add(layers.Dense(64, activation='relu',
input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model
model=build_model()
model.fit(train_data, train_targets, epochs=200, batch_size=32)
#try to get mse
y_pred = model.predict(train_data)
mse=np.mean((train_targets-y_pred)*(train_targets-y_pred))
print(mse)
这是最后3个纪元,mse
最后是
Epoch 198/200
404/404 [=======] - 0s 17us/step - loss: 3.4695 - mean_absolute_error: 1.3338
Epoch 199/200
404/404 [=======] - 0s 22us/step - loss: 3.5412 - mean_absolute_error: 1.3260
Epoch 200/200
404/404 [=======] - 0s 20us/step - loss: 3.2775 - mean_absolute_error: 1.2858
162.25934358457062
我在这里仅使用train_data
和train_targets
。为什么我得到的mse
甚至不接近每个时期报告的损失(mse
)?因此,预测距离目标还很近。请帮忙。