gpt4 book ai didi

python - python 中的数学公式不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:10 26 4
gpt4 key购买 nike

我一直在学习 python 机器学习,目前正在学习基础知识。我现在正在研究线性回归并尝试将一些数学公式实现到 python 代码中。我设法成功地写了一些公式,但是有一个我很难处理:(X - X 均值) * (Y - Y 均值)当我尝试打印它时,它总是给我一个错误“列表索引必须是整数或切片,而不是 numpy.float64”。

我曾尝试在网络上寻找相同的案例及其解决方案,但没有一个有效。


import numpy
import matplotlib.pyplot as plt

X_positions = numpy.array([2,3,4,5,6])
y_positions = numpy.array([4,5,6,5,7])
plt.plot([X_positions], [y_positions], 'ro')
plt.axis([0,10,0,10])

X_means = sum(X_positions) / len(X_positions)
y_means = sum(y_positions) / len(y_positions)

plt.plot([X_means], [y_means], 'go')
plt.axis([0,10,0,10])

X_minus_X_means = []
y_minus_y_means = []
X_minus_X_means_squared = []

for i in X_positions:
X_minus_X_means.append(i - X_means)

for i in y_positions:
y_minus_y_means.append(i - y_means)

for i in X_minus_X_means:
X_minus_X_means_squared.append(i ** 2)

X_minus_X_means_times_y_minus_y_means = []

#HERE IS THE PROBLEM
for i in X_minus_X_means and y_minus_y_means:
X_minus_X_means_times_y_minus_y_means.append(X_minus_X_means[i] * y_minus_y_means[i])


最佳答案

您真的应该尽可能使用内置的 numpy 操作和矢量化操作。

尝试这样的事情:

import numpy as np

import matplotlib.pyplot as plt

X_positions = np.array([2,3,4,5,6])
y_positions = np.array([4,5,6,5,7])
plt.plot([X_positions], [y_positions], 'ro')
plt.axis([0,10,0,10])

X_means = X_positions.mean()
y_means = y_positions.mean()

plt.plot([X_means], [y_means], 'go')
plt.axis([0,10,0,10])

X_minus_X_means = X_positions-X_means
y_minus_y_means = y_positions-y_means
X_minus_X_means_squared = X_minus_X_means**2
X_minus_X_means_times_y_minus_y_means = X_minus_X_means*y_minus_y_means

关于python - python 中的数学公式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com