python-numpy-相关性、回归、画图-np.polyfit(x,y,deg=1)

25 篇文章 1 订阅
14 篇文章 1 订阅
from scipy import stats

# Plot the illiteracy rate versus fertility
_ = plt.plot(illiteracy, fertility, marker='.', linestyle='none')

# Set the margins and label axes
plt.margins(0.02)
_ = plt.xlabel('percent illiterate')
_ = plt.ylabel('fertility')

# Show the plot
plt.show()

# Show the Pearson correlation coefficient
print(stats.pearsonr(illiteracy, fertility))


# Plot the illiteracy rate versus fertility
_ = plt.plot(illiteracy, fertility, marker='.', linestyle='none')
plt.margins(0.02)
_ = plt.xlabel('percent illiterate')
_ = plt.ylabel('fertility')

# Perform a linear regression using np.polyfit(): a, b
a, b = np.polyfit(illiteracy, fertility, 1)

# Print the results to the screen
print('slope =', a, 'children per woman / percent illiterate')
print('intercept =', b, 'children per woman')

# Make theoretical line to plot
x = np.array([0, 100])
y = a * x + b

# Add regression line to your plot
_ = plt.plot(x, y)

# Draw the plot
plt.show()

#计算rss

# Specify slopes to consider: a_vals
a_vals = np.linspace(0,0.1,200)


# Initialize sum of square of residuals: rss
rss = np.empty_like(a_vals)


# Compute sum of square of residuals for each value of a_vals
for i, a in enumerate(a_vals):
    rss[i] = np.sum((fertility - a*illiteracy - b)**2)


# Plot the RSS
plt.plot(a_vals, rss, '-')
plt.xlabel('slope (children per woman / percent illiterate)')
plt.ylabel('sum of square of residuals')


plt.show()


当你调用 np.polyfit(x, y, deg) 时,函数将返回您需要的多项式系数。 举例说明: 例1:我们有一组数据点(x,y):(1,2), (2,3), (3,4), (4,5)。现在我们要拟合这些数据,其中 deg=1。也就是说,我们将使用一次多项式拟合数据。也就是线性回归模型拟合数据。 代码如下: import numpy as np x = np.array([1, 2, 3, 4]) y = np.array([2, 3, 4, 5]) poly = np.polyfit(x, y, 1) print(poly) 输出结果: [1. 1.] 意思是 y = 1x + 1。也就是说,我们使用一次多项式(直线)拟合数据时,得到的斜率为1,截距为1。 例2:我们有另一组数据点(x,y):(1,2), (2,3), (3,4), (4,5),现在我们要拟合这些数据,deg=3。也就是说,我们将使用三次多项式拟合数据。 代码如下: import numpy as np x = np.array([1, 2, 3, 4]) y = np.array([2, 3, 4, 5]) poly = np.polyfit(x, y, 3) print(poly) 输出结果: [ 1.00000000e+00 -6.07153217e-16 -4.28867739e-16 3.85714286e+00] 意思是 y = 1x^3 + 0x^2 + 0x + 3.85714286,也就是说,我们使用三次多项式拟合数据时,得到的系数。 例3:我们有一组数据点(x,y):(1,2), (2,3), (3,4),现在我们要拟合这些数据,deg=2。也就是说,我们将使用二次多项式拟合数据。 代码如下: import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 3, 4]) poly = np.polyfit(x, y, 2) print(poly) 输出结果: [ 1.00000000e+00 -3.00000000e+00 4.00000000e+00] 意思是 y = 1x^2 - 3x + 4,也就是说,我们使用二次多项式拟合数据时,得到的系数。 例4:我们有一组数据点(x,y):(2,4), (4,6), (6,8),现在我们要拟合这些数据,deg=1。也就是说,我们将使用一次多项式拟合数据。 代码如下: import numpy as np x = np.array([2, 4, 6]) y = np.array([4, 6, 8]) poly = np.polyfit(x, y, 1) print(poly) 输出结果: [1. 2.] 意思是 y = 1x + 2,也就是说,我们使用一次多项式拟合数据时,得到的系数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值