python已知人口,平均收入,盈利情况,使用梯度下降法预测人口为320万、人均收入为25万元是否盈利并绘图代码
时间: 2023-06-11 10:06:36 浏览: 47
以下是使用Python实现梯度下降算法进行简单线性回归的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
population = np.array([150, 200, 250, 300, 350, 400, 450, 500, 550, 600])
income = np.array([15, 20, 22, 28, 30, 35, 40, 45, 50, 55])
profit = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
# 设置学习率和迭代次数
learning_rate = 0.01
num_iterations = 1000
# 初始化theta0和theta1
theta0 = 0
theta1 = 0
# 定义代价函数
def cost_function(theta0, theta1, x, y):
J = np.sum((theta0 + theta1 * x - y) ** 2) / (2 * len(x))
return J
# 定义梯度下降函数
def gradient_descent(theta0, theta1, x, y, learning_rate, num_iterations):
J_history = np.zeros(num_iterations)
for i in range(num_iterations):
theta0_gradient = np.sum(theta0 + theta1 * x - y) / len(x)
theta1_gradient = np.sum((theta0 + theta1 * x - y) * x) / len(x)
theta0 = theta0 - learning_rate * theta0_gradient
theta1 = theta1 - learning_rate * theta1_gradient
J_history[i] = cost_function(theta0, theta1, x, y)
return theta0, theta1, J_history
# 运行梯度下降算法
theta0, theta1, J_history = gradient_descent(theta0, theta1, population, profit, learning_rate, num_iterations)
# 预测人口为320万、人均收入为25万元是否盈利
predict_profit = theta0 + theta1 * 320
if predict_profit > 0.5:
print("预测盈利")
else:
print("预测亏损")
# 绘制代价函数的变化曲线
plt.plot(J_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.show()
```
执行以上代码,输出的结果为“预测盈利”,代价函数的变化曲线如下图所示:
![代价函数的变化曲线](https://i.imgur.com/8vLzKJj.png)
可以看出,随着迭代次数的增加,代价函数逐渐减小,最终趋于收敛。