You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow结合numpy使用时出现pandas AttributeError问题求助

问题解决方案

1. 修复Pandas依赖错误

报错AttributeError: module 'pandas' has no attribute 'Series'是由于Pandas库安装不完整或版本与TensorFlow不兼容导致的,执行以下命令重新安装适配版本:

  • 卸载现有Pandas:
    pip uninstall pandas -y
    
  • 安装兼容版本:
    pip install pandas==2.0.3
    

2. 修正代码逻辑错误

你的代码存在任务类型混淆、数据加载错误、可视化方法误用等问题,以下是完全修正后的可运行代码:

from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np

# 修正数据加载的解包格式
(x_train, y_train), (x_test, y_test) = keras.datasets.boston_housing.load_data()

# 数据标准化(回归任务必备步骤,消除特征量纲影响)
mean = x_train.mean(axis=0)
std = x_train.std(axis=0)
x_train = (x_train - mean) / std
x_test = (x_test - mean) / std

# 构建回归任务的神经网络结构
model = keras.Sequential([
    keras.layers.InputLayer(input_shape=(13,)),
    keras.layers.Dense(32, activation="relu"),
    keras.layers.Dense(16, activation="relu"),
    keras.layers.Dense(1)  # 回归任务输出层无需激活函数
])

# 配置回归任务的优化器、损失函数与评估指标
model.compile(optimizer="adam", loss="mse", metrics=["mae"])

# 训练模型,加入验证集监控过拟合
history = model.fit(x_train, y_train, epochs=50, validation_split=0.1)

# 生成预测结果
predictions = model.predict(x_test)

# 可视化真实房价与预测房价的对比
plt.figure(figsize=(10,6))
plt.scatter(y_test, predictions)
plt.xlabel("真实房价")
plt.ylabel("预测房价")
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
plt.title("真实房价 vs 预测房价")
plt.show()

# 可视化训练过程中的误差变化
plt.figure(figsize=(10,6))
plt.plot(history.history['mae'], label='训练集平均绝对误差')
plt.plot(history.history['val_mae'], label='验证集平均绝对误差')
plt.xlabel("训练轮次")
plt.ylabel("平均绝对误差")
plt.legend()
plt.title("训练误差变化曲线")
plt.show()

关键修正点说明

  • 数据加载:原代码错误解包load_data()的返回值,正确格式应为(x_train, y_train), (x_test, y_test)
  • 任务适配:波士顿房价是回归任务(预测连续数值),不能使用分类任务的sigmoid激活函数和sparse_categorical_crossentropy损失,需改用无激活输出层和mse(均方误差)损失
  • 数据预处理:回归任务必须对输入特征做标准化,否则模型无法有效收敛
  • 可视化修正:x_test是13维特征向量而非图像,不能用imshow展示,改用散点图呈现预测与真实值的关系
  • 模型优化:增加神经元数量,加入验证集监控训练过程,提升模型拟合能力与泛化性

内容的提问来源于stack exchange,提问作者Rick Astley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:42:02