我正在尝试第一次使用Scipy和Scipy最小化.我已经阅读了文档并看过一些YT教程,似乎每次我们都需要最小化一个变量时,我们都需要对当前问题进行数学表示.
就我而言,我有一个代表我的数据集的玩具示例.我有 :
>产品清单
>客户清单和关于他们是否购买产品的二进制答复
>我正在尝试对客户进行分类的多个集群.存储的值表示群集的中心,在优化步骤之前将其设置为0.
我所做的工作非常基础,对于每个群集,我都在计算每个群集值和客户交易之间的平方差的平方根.这样每个客户对于每个群集都有一个距离值.
然后,我为每个客户选择最低的距离值并将其汇总.
>这是我要最小化的总距离,这是我的目标
>决策变量都是集群中的全0,
>约束(Bound?),聚类中心应保持在0.00和1.00之间
当我使用exp时,函数不是线性的,因此我在使用SLSQP,我的猜测是尝试一下:
sol = minimize(total_distance_to_minimize, dataframe[clusters.keys()], method='SLSQP', Bounds=((0,1)), options={'disp'=True})
以下玩具示例:
#utf8
import pandas as pd
import numpy as np
from scipy.optimize import minimize, Bounds
import math
#dict holoding distances between customers and clusters
distances = dict()
product_list = ['banana juice','pinnaple juice' ,
'maracudja',
'cupuacu',
'goava',
'coconut',
'apple',
'grappe',
'acai']
customer_dict = {'Bilbon Saquet' :[0,1,0,1,0,1,0,0,0],
'Gandalft':[0,0,0,1,0,0,0,0,0],
'Thorin':[1,1,1,0,0,0,0,0,0],
'Smaug':[0,0,1,1,0,1,0,0,1],
'Radagast':[0,1,1,1,1,1,0,0,0],
'Elrond':[0,0,0,1,0,1,1,0,1],
'Balin':[0,0,0,0,0,1,0,0,0]}
clusters = {'Clusters 1' :[0,0,0,0,0,0,0,0,0],
'Clusters 2':[0,0,0,0,0,0,0,0,0],
'Clusters 3':[0,0,0,0,0,0,0,0,0],
'Clusters 4':[0,0,0,0,0,0,0,0,0]}
data = pd.DataFrame(customer_dict, index= product_list)
clusters = pd.DataFrame(clusters, index=product_list)
dataframe = pd.concat([data, clusters], axis='columns')
for k in clusters :
for customer in customer_dict:
distances.setdefault(customer, [])
distances[customer].append(math.sqrt(((dataframe[k]-dataframe[customer])**2).sum()))
distances = pd.DataFrame(distances, index=clusters.keys())
total_distance_to_minimize = distances.min().sum()
我是否可以创建很多不同的DataFrame以使其正常工作?
使用Scipy.minimize最小化总距离的正确方法是什么?
解决方法:
您可以按照以下步骤在问题中使用最小化函数.
决策变量必须是一维数组.因此,我将您的决策变量展平为
init_vars = np.zeros(len(product_list)*clusters.shape[1])
目标函数需要定义,并且必须作为可调用函数输入到优化器中.
def obj_fn(dec_vars):
distances={}
temp_clusters = pd.DataFrame(dec_vars.reshape((len(product_list),clusters.shape[1])),
index=product_list,columns= clusters.columns)
temp_df= pd.concat([data, temp_clusters], axis='columns')
for k in clusters :
for customer in customer_dict:
distances.setdefault(customer, [])
distances[customer].append(math.sqrt(((temp_df[k]-temp_df[customer])**2).sum()))
distances = pd.DataFrame(distances, index=clusters.keys())
return distances.min().sum()
现在,我们必须按顺序设置每个决策变量的界限.将所有内容放在一起,我们将使用优化器功能,如下所示:
sol = minimize(obj_fn, init_vars , method='SLSQP', bounds=[(0,1) for _ in init_vars],tol =0,options={'maxiter':50,'eps':0.01})
对于给定的示例,求解器给出的最优解为
5.562980209812645
该解决方案可以通过以下方式检索
dec_vars = sol.x
temp_clusters = pd.DataFrame(dec_vars.reshape((len(product_list),clusters.shape[1])),
index=product_list,columns= clusters.columns)
temp_df= pd.concat([data, temp_clusters], axis='columns')
print(temp_df)
输出:
Balin Bilbon Saquet Elrond Gandalft Radagast Smaug \
banana juice 0 0 0 0 0 0
pinnaple juice 0 1 0 0 1 0
maracudja 0 0 0 0 1 1
cupuacu 0 1 1 1 1 1
goava 0 0 0 0 1 0
coconut 1 1 1 0 1 1
apple 0 0 1 0 0 0
grappe 0 0 0 0 0 0
acai 0 0 1 0 0 1
Thorin Clusters 1 Clusters 2 Clusters 3 Clusters 4
banana juice 1 0.685121 3.964158e-16 2.464523e-03 1.663972e-01
pinnaple juice 1 1.000000 9.976724e-01 7.504636e-03 4.644470e-01
maracudja 1 1.000000 9.972195e-01 7.066747e-01 1.774573e-01
cupuacu 0 1.000000 9.959170e-01 9.999912e-01 5.891786e-01
goava 0 0.993446 9.963349e-01 3.898192e-04 1.606294e-02
coconut 0 1.000000 9.957576e-01 9.999994e-01 5.877336e-01
apple 0 0.996145 1.676883e-16 2.963329e-01 2.001538e-02
grappe 0 0.000000 2.918387e-16 2.711116e-18 1.562419e-17
acai 0 0.995514 1.584998e-16 9.947202e-01 1.472500e-02