【发布时间】:2020-08-06 22:29:42
【问题描述】:
有趣的是,使用 np.mean() 或 mean() 给了我不同的输出。
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs = np.array([1, 2, 3, 4, 5, 6])
ys = np.array([5, 4, 6, 5, 6, 7])
def best_fit_slope(xs, ys):
numerator = (mean(xs)*mean(ys)) - mean(xs*ys)
denominator = mean(xs)**2 - mean(xs**2)
return numerator/denominator
m = best_fit_slope(xs, ys)
print(m)
输出>>>
0.8333333333333334
但是如果我用 np.mean() 替换 mean()
输出 >>> 0.42857142857142866.
我关注了这个视频:this video。他只是使用 mean() 并给出了 0.42857 的输出。谁能解释为什么有区别?我知道大多数线性代数运算或涉及数组的运算,我更喜欢使用 np.mean()。
【问题讨论】:
-
请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。
-
你有 五个
mean操作。哪些返回值您没有预料到?函数定义有什么区别?我们希望您进行基本的诊断跟踪以确定混淆点。 “我的程序给出了不同的输出”比我们对你的期望更笼统——输入一些中间的prints 来找出你在哪里感到困惑。 -
有趣的
mean似乎是截断/舍入。也许它会在结果上调用np.int64?
标签: python arrays numpy linear-regression