Keras中model.evaluate()返回的是 loss value & metrics values

博客介绍了Keras中model.evaluate()函数的相关信息,该函数返回损失值和选定的指标值,如精度accuracy。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数文档

Keras中model.evaluate()返回的是 损失值你选定的指标值(例如,精度accuracy)。

 

 

import numpy as np import pandas as pd from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # 加载数据集 boston = load_boston() X = boston.data y = boston.target feature_names = boston.feature_names #转换为DataFrame data = pd.DataFrame(X, columns=feature_names) data['MEDV'] = y # 显示前5行数据 print(data.head()) # 数据标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) #划分训练集和测试集 X_train,X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42) #训练集:404个样本(80%),测试集:102个样本(20%) print(f"训练集样本数: {len(X_train)}") print(f"测试集样本数: {len(X_test)}")from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # 构建模型 model = Sequential([ Dense(64, activation='relu', input_shape=(13,)), Dense(32, activation='relu'), Dense(1) # 回归问题不需要激活函数 # 编译模型 model.compile(optimizer='adam', loss='mse', metrics=['mae']) # 显示模型摘要 model.summary()# 训练模型 history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.2, verbose=1) # 绘制训练和验证的损失曲线 import matplotlib.pyplot as plt plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.show() # 绘制训练和验证的MAE曲线 plt.plot(history.history['mae'], label='Training MAE') plt.plot(history.history['val_mae'], label='Validation MAE') plt.title('Model MAE') plt.xlabel('Epoch') plt.ylabel('MAE') plt.legend() plt.show()# 在测试集上评估模型 test_loss, test_mae = model.evaluate(X_test, y_test, verbose=0) print(f"测试集MSE: {test_loss:.4f}") print(f"测试集MAE: {test_mae:.4f} (千美元)") # 随机选择5个测试样本进行预测 import random sample_indices = random.sample(range(len(X_test)), 5) samples = X_test[sample_indices] true_values = y_test[sample_indices] predictions = model.predict(samples).flatten() # 显示预测结果 results = pd.DataFrame({ 'True Value (k$)': true_values, 'Predicted Value (k$)': predictions, 'Absolute Error (k$)': np.abs(true_values - predictions) }) print(results)这串代码的运行结果是什么
05-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值