鱼C论坛

 找回密码
 立即注册
12
返回列表 发新帖
楼主: Terence888

损失上百万如何解决

[复制链接]
 楼主| 发表于 2024-10-26 16:20:31 | 显示全部楼层
FishC 发表于 2024-10-26 16:02
出现这个错误的原因是数据框 `X_test` 仍然包含一些无法转换为数值型的数据。我们需要对 `X_test` 做进 ...
  1. MSSubClass               float64
  2. LotArea                  float64
  3. OverallQual              float64
  4. OverallCond              float64
  5. YearBuilt                float64
  6.                           ...   
  7. SaleCondition_AdjLand       bool
  8. SaleCondition_Alloca        bool
  9. SaleCondition_Family        bool
  10. SaleCondition_Normal        bool
  11. SaleCondition_Partial       bool
  12. Length: 153, dtype: object
复制代码


以上是结果 ,说明数据类型都是数值型了吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-10-26 16:20:39 | 显示全部楼层
Terence888 发表于 2024-10-26 16:20
MSSubClass               float64
LotArea          ...


您提供的结果显示,除了 `bool` 类型外,其他都是 `float64` 类型,这些都可以被转换为数值类型。`bool` 类型的列也可以直接转换为 `int` 类型。

在将数据转换为 PyTorch 张量之前,可以按以下步骤进行处理:

  1. # 将布尔型转为整数型
  2. X_test = X_test.astype(int)

  3. # 转换为 PyTorch 张量
  4. X_test_tensor = torch.tensor(X_test.values, dtype=torch.float32)

  5. # 进行预测
  6. with torch.no_grad():
  7.     test_output = dnn_model(X_test_tensor)
  8.     test_output_numpy = test_output.numpy().flatten()  # 将张量转换为 numpy 数组
  9.    
  10.     # 假设 X_test 有一个 Id 列用于唯一标识,如果没有需要自行定义
  11.     submission = pd.DataFrame({'Id': X_test.index, 'SalePrice': test_output_numpy})
  12.     submission.to_csv('submission.csv', index=False)

  13. print("Submission file created successfully.")
复制代码


这样,可以确保您的数据框中,所有的布尔型和浮点型数据都不会导致类型问题。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-10-26 17:01:51 | 显示全部楼层
FishC 发表于 2024-10-26 16:20
您提供的结果显示,除了 `bool` 类型外,其他都是 `float64` 类型,这些都可以被转换为数值类型。`bool ...
  1. test_data['Id']
  2. 0       1461
  3. 1       1462
  4. 2       1463
  5. 3       1464
  6. 4       1465
  7.         ...
  8. 1454    2915
  9. 1455    2916
  10. 1456    2917
  11. 1457    2918
  12. 1458    2919
  13. Name: Id, Length: 1459, dtype: int64
复制代码

test_data的Id值如何作为新dataframe的id列,以下代码存在报错
  1. #模型期望输入的是PyTorch 张量,先将 DataFrame 转换为张量

  2. X_test = X_test.astype(int)# 将布尔型转为整数型
  3. X_test_tensor = torch.tensor(X_test.values, dtype=torch.float32)# 转换为 PyTorch 张量

  4. with torch.no_grad():
  5.     test_output = dnn_model(X_test_tensor)
  6.     test_output_numpy = test_output.numpy().flatten() # 将张量转换为 numpy 数组
  7.     submission = pd.DataFrame({'Id': test_data['Id'].values, 'SalePrice': test_output})
  8.     #submission.to_csv('submission.csv', index=False)
复制代码


错误如下:
  1. ---------------------------------------------------------------------------
  2. ValueError                                Traceback (most recent call last)
  3. Cell In[94], line 9
  4.       7 test_output = dnn_model(X_test_tensor)
  5.       8 test_output_numpy = test_output.numpy().flatten() # 将张量转换为 numpy 数组
  6. ----> 9 submission = pd.DataFrame({'Id': test_data['Id'].values, 'SalePrice': test_output})
  7.      10 #submission.to_csv('submission.csv', index=False)

  8. File /opt/conda/lib/python3.10/site-packages/pandas/core/frame.py:778, in DataFrame.__init__(self, data, index, columns, dtype, copy)
  9.     772     mgr = self._init_mgr(
  10.     773         data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
  11.     774     )
  12.     776 elif isinstance(data, dict):
  13.     777     # GH#38939 de facto copy defaults to False only in non-dict cases
  14. --> 778     mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  15.     779 elif isinstance(data, ma.MaskedArray):
  16.     780     from numpy.ma import mrecords

  17. File /opt/conda/lib/python3.10/site-packages/pandas/core/internals/construction.py:503, in dict_to_mgr(data, index, columns, dtype, typ, copy)
  18.     499     else:
  19.     500         # dtype check to exclude e.g. range objects, scalars
  20.     501         arrays = [x.copy() if hasattr(x, "dtype") else x for x in arrays]
  21. --> 503 return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)

  22. File /opt/conda/lib/python3.10/site-packages/pandas/core/internals/construction.py:119, in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate)
  23.     116         index = ensure_index(index)
  24.     118     # don't force copy because getting jammed in an ndarray anyway
  25. --> 119     arrays, refs = _homogenize(arrays, index, dtype)
  26.     120     # _homogenize ensures
  27.     121     #  - all(len(x) == len(index) for x in arrays)
  28.     122     #  - all(x.ndim == 1 for x in arrays)
  29.    (...)
  30.     125
  31.     126 else:
  32.     127     index = ensure_index(index)

  33. File /opt/conda/lib/python3.10/site-packages/pandas/core/internals/construction.py:629, in _homogenize(data, index, dtype)
  34.     626         val = dict(val)
  35.     627     val = lib.fast_multiget(val, oindex._values, default=np.nan)
  36. --> 629 val = sanitize_array(val, index, dtype=dtype, copy=False)
  37.     630 com.require_length_match(val, index)
  38.     631 refs.append(None)

  39. File /opt/conda/lib/python3.10/site-packages/pandas/core/construction.py:633, in sanitize_array(data, index, dtype, copy, allow_2d)
  40.     631     else:
  41.     632         data = np.array(data, copy=copy)
  42. --> 633     return sanitize_array(
  43.     634         data,
  44.     635         index=index,
  45.     636         dtype=dtype,
  46.     637         copy=False,
  47.     638         allow_2d=allow_2d,
  48.     639     )
  49.     641 else:
  50.     642     _sanitize_non_ordered(data)

  51. File /opt/conda/lib/python3.10/site-packages/pandas/core/construction.py:659, in sanitize_array(data, index, dtype, copy, allow_2d)
  52.     656             subarr = cast(np.ndarray, subarr)
  53.     657             subarr = maybe_infer_to_datetimelike(subarr)
  54. --> 659 subarr = _sanitize_ndim(subarr, data, dtype, index, allow_2d=allow_2d)
  55.     661 if isinstance(subarr, np.ndarray):
  56.     662     # at this point we should have dtype be None or subarr.dtype == dtype
  57.     663     dtype = cast(np.dtype, dtype)

  58. File /opt/conda/lib/python3.10/site-packages/pandas/core/construction.py:718, in _sanitize_ndim(result, data, dtype, index, allow_2d)
  59.     716     if allow_2d:
  60.     717         return result
  61. --> 718     raise ValueError(
  62.     719         f"Data must be 1-dimensional, got ndarray of shape {data.shape} instead"
  63.     720     )
  64.     721 if is_object_dtype(dtype) and isinstance(dtype, ExtensionDtype):
  65.     722     # i.e. NumpyEADtype("O")
  66.     724     result = com.asarray_tuplesafe(data, dtype=np.dtype("object"))

  67. ValueError: Data must be 1-dimensional, got ndarray of shape (1459, 1) instead
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-10-26 17:07:21 | 显示全部楼层
Terence888 发表于 2024-10-26 17:01
test_data
0       1461
1       1462
2       146 ...


错误是因为 `test_output` 是一个二维张量。需要将其转换为一维数组。修正如下:

  1. # 模型期望输入的是 PyTorch 张量,先将 DataFrame 转换为张量
  2. X_test = X_test.astype(int)  # 将布尔型转为整数型
  3. X_test_tensor = torch.tensor(X_test.values, dtype=torch.float32)  # 转换为 PyTorch 张量

  4. with torch.no_grad():
  5.     test_output = dnn_model(X_test_tensor)
  6.     test_output_numpy = test_output.numpy().flatten()  # 将张量转换为一维 numpy 数组
  7.     submission = pd.DataFrame({'Id': test_data, 'SalePrice': test_output_numpy})
  8.     submission.to_csv('submission.csv', index=False)

  9. print("Submission file created successfully.")
复制代码


### 修正要点:

1. **使用 `flatten()` 将张量展平**:
   - 确保 `test_output` 在转换为 numpy 数组时是一维的。

2. **使用 `test_data` 作为 `Id`**:
   - 确保 `test_data` 是一个包含唯一标识符的有效序列(例如 DataFrame 或 Series)。

这样,您的 `submission` DataFrame 将正确映射 `Id` 列和 `SalePrice` 列。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-19 17:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表