赞
踩
数据
求解:当房屋面积为55平方时,租赁价格是多少?给出代码与运行结果图
主要是用数学推导出最小二乘法的公式,然后求出来所需要的各个参数,预测出来最终结果,有点像数学建模
不要抄袭代码
import matplotlib.pyplot as plt from pylab import mpl #导入数据源 x = [10, 15, 20, 30, 50, 60, 60, 70] y = [0.8, 1, 1.8, 2, 3.2, 3, 3.1, 3.5] #计算一元表达式的参数,根据最小二乘法表达式计算,推出各个参数并代入表达式,计算出来最终结果 def liner_fitting(data_x, data_y): size = len(data_x) i = 0 sum_xy = 0 sum_y = 0 sum_x = 0 sum_sqare_x = 0 while i < size: sum_xy += data_x[i] * data_y[i] sum_y += data_y[i] sum_x += data_x[i] sum_sqare_x += data_x[i] * data_x[i] i += 1 average_x = sum_x / size average_y = sum_y / size return_k = (size * sum_xy - sum_x * sum_y) / (size * sum_sqare_x - sum_x * sum_x) return_b = average_y - average_x * return_k return [return_k, return_b] #根据给出的参数值计算出来拟合曲线上的y值集合 def calculate(datax, k, b): datay = [] for x in datax: datay.append(k * x + b) return datay """完成函数的绘制""" def draw(datax, new_datay, old_datay): mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False plt.plot(datax, new_datay,"bs--", label="根据房屋面积预测房价") #scatter函数绘制散点图 plt.scatter(datax, old_datay, label="原数据离散值",edgecolors="green") plt.title("根据房屋面积预测房价") plt.show() data = liner_fitting(x, y) draw_data = calculate(x, data[0], data[1]) print(data[0] * eval(input()) + data[1]) draw(x, draw_data, y)
实验结果图
预测结果:
点个
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。