python中的数学公式不起作用

问题描述 投票:1回答:5

我一直在学习python中的机器学习,目前正在学习基础知识。我现在正在研究线性回归并尝试将一些数学公式实现为python代码。我设法成功地写了一些公式但是有一个我很难用:(X - Xmeans)*(Y - Ymeans)它总是给我一个错误“列表索引必须是整数或切片,而不是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])


python python-3.x numpy
5个回答
3
投票

你应该尽可能使用内置的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

1
投票

代替

for i in X_minus_X_means and y_minus_y_means:

试着写

for i in range(len(X_minus_X_means)):

否则i不是整数,不能用作索引


0
投票

也许该分裂正在产生一个float,导致该指数为非整数?

X_means = sum(X_positions) / len(X_positions)

对于python3中的整数除法,可以使用双斜杠运算符//

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

你也可以使用ceilfloorroundint(val)


0
投票

X_minus_X_meansy_minus_y_means都是名单

y_minus_y_means包含价值

[-1.4000000000000004,
 -0.40000000000000036,
 0.5999999999999996,
 -0.40000000000000036,
 1.5999999999999996]

所以基本上在for i in X_minus_X_means and y_minus_y_means:i值在type numpy.float64和内部循环中计算,你使用X_minus_X_means访问y_minus_y_meansindex的值,这是i一个float


0
投票

虽然我完全支持并更喜欢向量化操作,但我认为您应该了解名为zip的函数,这对于并行迭代两个(或更多)列表的情况很有用。所以在你的情况下,有问题的部分应该改为以下,避免任何索引i

for x, y in zip(X_minus_X_means, y_minus_y_means):
    X_minus_X_means_times_y_minus_y_means.append(x * y)
© www.soinside.com 2019 - 2024. All rights reserved.