文章目录
-
-
- (一)、读取数据
- (二)、获得拟合函数并绘制图象
- (三)、通过计算拟合优度评价拟合函数
- (四)、综合代码
- (五)、结果输出
关于Python数据分析在数学建模中的更多相关应用:Python数据分析在数学建模中的应用汇总(持续更新中!)
(一)、读取数据
def read(file):
wb = xlrd.open_workbook(filename=file)
sheet = wb.sheet_by_index(0)
rows = sheet.nrows
all_content = []
for j in range(0, 2):
temp = []
for i in range(1,rows) :
cell = sheet.cell_value(i, j)
temp.append(cell)
all_content.append(temp)
temp = []
return np.array(all_content)
(二)、获得拟合函数并绘制图象
def temp1(datas):
x = datas[0]
y = datas[1]
n = np.size(answer1, axis = 1)
k = (n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
b = (np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
las = k*x + b
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.set_xlim([min(x)-0.5, max(x)+0.5])
ax1.set_ylim([min(y) -0.5, max(y) +0.5])
plt.plot(x,las,'k',label='拟合函数')
plt.plot(x,y,'o',label = '样本数据')
plt.grid()
ax1.legend(loc = 'best')
return [k,b]
(三)、通过计算拟合优度评价拟合函数
def judge(datas,k,b):
x = datas[0]
y = datas[1]
z = k * x + b
SST = np.sum(np.power(y - np.average(y),2))
SSE = np.sum(np.power(y - z, 2))
SSR = np.sum(np.power(z - np.average(y),2))
R_2 = SSR / SST
print('k = ',k)
print('b = ',b)
print('SST = ',SST)
print('SSE = ',SSE)
print('SSR = ',SSR)
print('R_2 = ',R_2)
(四)、综合代码
"""
Created on Mon Jul 29 11:03:49 2019
@author: lenovo
"""
import xlrd
import numpy as np
import matplotlib.pyplot as plt
def read(file):
wb = xlrd.open_workbook(filename=file)
sheet = wb.sheet_by_index(0)
rows = sheet.nrows
all_content = []
for j in range(0, 2):
temp = []
for i in range(1,rows) :
cell = sheet.cell_value(i, j)
temp.append(cell)
all_content.append(temp)
temp = []
return np.array(all_content)
def temp1(datas):
x = datas[0]
y = datas[1]
n = np.size(answer1, axis = 1)
k = (n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
b = (np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
las = k*x + b
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.set_xlim([min(x)-0.5, max(x)+0.5])
ax1.set_ylim([min(y) -0.5, max(y) +0.5])
plt.plot(x,las,'k',label='拟合函数')
plt.plot(x,y,'o',label = '样本数据')
plt.grid()
ax1.legend(loc = 'best')
return [k,b]
def judge(datas,k,b):
x = datas[0]
y = datas[1]
z = k * x + b
SST = np.sum(np.power(y - np.average(y),2))
SSE = np.sum(np.power(y - z, 2))
SSR = np.sum(np.power(z - np.average(y),2))
R_2 = SSR / SST
print('k = ',k)
print('b = ',b)
print('SST = ',SST)
print('SSE = ',SSE)
print('SSR = ',SSR)
print('R_2 = ',R_2)
answer1 = read('C:\\Users\\lenovo\\Desktop\\数学建模\\拟合算法\\第4讲.拟合7.21\\代码和例题数据\\data1.xlsx')
answer2 = temp1(answer1)
judge(answer1,answer2[0],answer2[1])
(五)、结果输出