线性规划-整数规划

#!/usr/bin/env python

# -*- encoding: utf-8 -*-

'''
@Author  :   {Jack Zhao}

@Time    :   2019/11/1 8:54

@Contact :   {[email protected]}

@Desc    :  第一题
'''
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pulp as pulp


DATA_FILE = './xiaoshou.xlsx'

#绘制拟合曲线
def plot_linear(x,y):
	plt.plot(x,y,'ko--')
	plt.xlabel('advertisement')
	plt.ylabel('sale')
	plt.title("Relation curves")
	plt.savefig('../result/q1.png')

#预测结果分析
def forcast():
	"""
	预测
	"""
	df = pd.read_excel(DATA_FILE)
	data = np.array(df)
	X = data[:,2:5]  # 取特征列
	y = data[:,1]  # 取销售量

	# 分割数据集
	X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1 / 3, random_state=10)
	#print(X_train)
	# 建立线性回归模型
	linear_reg_model = LinearRegression()
	# 模型训练
	linear_reg_model.fit(X_train, y_train)
	# 验证模型
	r2_score = linear_reg_model.score(X_test, y_test)
	print('模型的R2值', r2_score)
	if r2_score>0.95:
		print('符合线性回归假设!')
		print('模型的系数', linear_reg_model.coef_)
		# 输出方程
		a = list(linear_reg_model.coef_)
		print('方程为: y = %f * X1 + %f * X2 + %f * X3' % (a[0], a[1], a[2]))

		# 单个样本预测
		print('下列为单个样本检验:')
		i = 2
		single_test_feat = X_test[i, :]
		y_true = y_test[i]
		y_pred = linear_reg_model.predict([single_test_feat])
		print('样本特征:', single_test_feat)
		print('真实销售量:{},预测销售量:{}'.format(y_true, y_pred))
		if abs(y_true-y_pred)<3:
			print('预测误差较小,满足条件!')
		else:
			print('预测误差较大,请重新验证模型!')
	else:
		print('不满足线性回归假设!')

	#销售增长10%,其余数据不变
	print('下面为对广告收入的灵敏度分析')
	print('%f%%'%(a[1]*100-100))

# 求解整数规划
def solve_ilp(objective , constraints) :
    #print(objective)
    #print(constraints)
    prob = pulp.LpProblem('LP1' , pulp.LpMaximize)
    prob += objective
    for cons in constraints :
        prob += cons
    print(prob)
	#判断是否求解成功
    status = prob.solve()
    if status != 1 :
        #print 'status'
        #print status
        return None
    else :
        #return [v.varValue.real for v in prob.variables()]
		#返回整数解
        return [v.varValue.real for v in prob.variables()]



if __name__=='__main__':
	df = pd.read_excel('../code/xiaoshou.xlsx')
	data = np.array(df)
	advertisment = list(data[:,3])
	sale = list(data[:,1])
	plot_linear(advertisment,sale)
	plt.show()
	print("\n拟合曲线已绘制完成\n")
	print("\n\n\n下面是需求预测\n")
	forcast()
	print('\n\n\n下面是整数规划\n')
	# 解如下整数线性规划
	# maximize  z = c*x = 192*x1 + 36*x2 + 12*x3
	# x0_bounds = (5,)
	# x1_bounds = (3,)
	# x2_bounds = (0, 2)
	# 三个约束条件
	V_NUM = 3
	# 变量,直接设置下限,并设置cat类型为整数解
	X1 = pulp.LpVariable('X1', lowBound=5, cat=pulp.LpInteger)
	X2 = pulp.LpVariable('X2', lowBound=3, cat=pulp.LpInteger)
	X3 = pulp.LpVariable('X3', lowBound=0, cat=pulp.LpInteger)
	variables = [X1, X2, X3]

	# 目标函数
	c = [192, 36, 12]
	objective = sum([c[i] * variables[i] for i in range(0, V_NUM)])
	# 约束条件
	constraints = []
	a1 = [150000, 24000, 120000]
	constraints.append(sum([a1[i] * variables[i] for i in range(0, V_NUM)]) <= 1000000)
	a2 = [150000, 0, 0]
	constraints.append(sum([a2[i] * variables[i] for i in range(0, V_NUM)]) >= 650000)
	a3 = [0, 0, 2]
	constraints.append(sum([a3[i] * variables[i] for i in range(0, V_NUM)]) <= 2)
	print(constraints)

	res = solve_ilp(objective, constraints)
	print("\n求解最优结果为:户外广告%d,专业杂志%d,其他广告%d"%(res[0],res[1],res[2]))
	print("预计最优展露效果为:%d\n"%(192*res[0] + 36*res[1] + 12*res[2]))





发布了101 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_40539952/article/details/103423162