python - 将数据集中的特征添加到函数中会导致 "TypeError: can' t 将类型 'ndarray' 转换为分子/分母”

标签 python machine-learning scikit-learn dataset linear-regression

该任务要求您加载糖尿病数据集的特征并编写自己的最适合训练数据的行。

我已经编写了最佳拟合算法所需的行,但是当尝试向其中添加训练数据时,我收到此错误:

“类型错误:无法将类型‘ndarray’转换为分子/分母”

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from statistics import mean

diabetes = datasets.load_diabetes()
diabetes_X = diabetes.data[:, np.newaxis, 2]

diabetes_X_train = diabetes_X[:-20] #creating the testing and training data 
diabetes_X_test = diabetes_X[-20:]

diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]

## The below code is where the issue is occurring 

xs = np.array(diabetes_X_train, dtype=np.float64)
ys = np.array([diabetes_y_train, dtype=np.float64)

##the algorithm to calculate the line of best  

def best_fit_slope_and_intercept(xs,ys):
    m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
         ((mean(xs)*mean(xs)) - mean(xs*xs)))

    b = mean(ys) - m*mean(xs)

    return m, b

m, b = best_fit_slope_and_intercept(xs,ys)

print(m,b)

我知道将所需数据转换为正确的格式是问题所在,但经过研究后,我无法找到正确的方法。

感谢所有有关如何根据需要正确连接或转换训练数据的意见。

最佳答案

在我看来,处理数据的最佳格式是 DataFrame。 您可以轻松地制作这样的数据框:

urdataframe={'headername': bestfitted}
urdataframe=pd.DataFrames(data=urdataframe)

然后您可以轻松联系您的数据框,例如:

finaldata=pd.concat((traindata,urdataframe),axis=1)

您可以在 DataFrames 上执行所有机器学习功能,并且不太可能出现错误

关于python - 将数据集中的特征添加到函数中会导致 "TypeError: can' t 将类型 'ndarray' 转换为分子/分母”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59511539/

相关文章:

python - ipython笔记本中的Unicode

machine-learning - 比自组织 map 更好或替代的方法来获得数据的基本理解/关系

r - R 中 KKNN 包中的最近邻在使用整个数据集时给出垃圾索引值

python - 值错误: setting an array element with a sequence while training KD TRee on TFIDF

tensorflow - 如何使用 tensorflow 数据集训练 sklearn 模型?

python - 带有 cssselct 的 scrapy

python - newrelic 和 zope 出错

python - 使用 Virtualenv 在 Ubuntu 上安装 Pip NLTK 问题

excel - 将值替换为该列的平均值 - 许多列

python - 如何提取梯度提升分类器的决策规则