使用xlogit的MultinomialLogit报错:y值不一致问题求助
多项Logit模型(Multinomial Logit)xlogit库运行报错问题
我正在学习多项Logit模型,使用xlogit库运行代码时遭遇ValueError,提示**"inconsistent 'y' values. Make sure the data has one choice per sample"**。
已将宽格式数据转为长格式,y(DEPVAR_1)取值为{1,2,3,4}对应四个备选方案,y与alt维度均为(1420,)且无缺失值,尝试reshape时又报错**"y must be an array of one dimension in long format"**,现寻求解决该y值不一致问题的建议。
运行代码
# Long format from xlogit.utils import wide_to_long ATUS_data_LA_2020_Long = wide_to_long(ATUS_data_LA_2020_wide, id_col='custom_id', alt_name='alt', sep='_', alt_list=['Non-Shopping', 'In-store Shopping', 'Online Shopping', 'Both'], empty_val=0, alt_is_prefix=True) # List of variables index_var_names = ['MSASIZE','FAMINCOME','AGE_1','SEX','EDUC','EMPSTAT','DIFFMOB_1','FSTRUC'] # Reshape y = ATUS_data_LA_2020_Long['DEPVAR_1'].values.ravel() # reshape 1 dimension alt = ATUS_data_LA_2020_Long['alt'].values.ravel() # reshape 1 dimension # Model from xlogit import MultinomialLogit model = MultinomialLogit() model.fit(X=ATUS_data_LA_2020_Long[index_var_names], y=y, varnames=index_var_names, ids=ATUS_data_LA_2020_Long['custom_id'], alts=alt, fit_intercept=True, weights=np.asarray(ATUS_data_LA_2020_Long['WEIGHT'])) model.summary()
报错信息
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[14], line 40 38 from xlogit import MultinomialLogit 39 model = MultinomialLogit() ---> 40 model.fit(X=ATUS_data_LA_2020_Long[index_var_names], 41 y=y, 42 varnames=index_var_names, 43 ids=ATUS_data_LA_2020_Long['custom_id'], 44 alts=alt, 45 fit_intercept=True, 46 weights=np.asarray(ATUS_data_LA_2020_Long['WEIGHT'])) 47 model.summary() File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\xlogit\multinomial_logit.py:139, in MultinomialLogit.fit(self, X, y, varnames, alts, ids, isvars, weights, avail, base_alt, fit_intercept, init_coeff, maxiter, random_state, tol_opts, verbose, robust, num_hess, scale_factor) 134 self._validate_inputs(X, y, alts, varnames, isvars, ids, weights) 136 self._pre_fit(alts, varnames, isvars, base_alt, fit_intercept, maxiter) 138 betas, X, y, weights, avail, Xnames, scale = \ --> 139 self._setup_input_data(X, y, varnames, alts, ids, 140 isvars=isvars, weights=weights, avail=avail, 141 init_coeff=init_coeff, 142 random_state=random_state, verbose=verbose, 143 predict_mode=False, scale_factor=scale_factor) 145 tol = {'ftol': 1e-10} 146 if tol_opts is not None: File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\xlogit\multinomial_logit.py:276, in MultinomialLogit._setup_input_data(self, X, y, varnames, alts, ids, isvars, weights, avail, base_alt, fit_intercept, init_coeff, random_state, verbose, predict_mode, scale_factor) 271 def _setup_input_data(self, X, y, varnames, alts, ids, isvars=None, 272 weights=None, avail=None, base_alt=None, fit_intercept=False, 273 init_coeff=None, random_state=None, verbose=1, predict_mode=False, 274 scale_factor=None): 275 self._check_long_format_consistency(ids, alts) --> 276 y = self._format_choice_var(y, alts) if not predict_mode else None 277 X, Xnames = self._setup_design_matrix(X) 278 N, J, K = X.shape File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\xlogit\_choice_model.py:193, in ChoiceModel._format_choice_var(self, y, alts) 191 return y1h 192 else: --> 193 raise ValueError("inconsistent 'y' values. Make sure the " 194 "data has one choice per sample") ValueError: inconsistent 'y' values. Make sure the data has one choice per sample
解决建议
修正y变量的标记逻辑:xlogit要求长格式数据中,每个样本(
custom_id)对应的多条备选方案行里,只有选中的那个方案对应的y值为1,其余为0,而非直接用1-4表示选中的方案编号。可按以下代码调整:# 给备选方案映射对应编号,匹配DEPVAR_1的1-4取值 alt_mapping = { 'Non-Shopping': 1, 'In-store Shopping': 2, 'Online Shopping': 3, 'Both': 4 } ATUS_data_LA_2020_Long['alt_code'] = ATUS_data_LA_2020_Long['alt'].map(alt_mapping) # 生成正确的选择标记:选中的方案y=1,其余为0 ATUS_data_LA_2020_Long['y'] = (ATUS_data_LA_2020_Long['alt_code'] == ATUS_data_LA_2020_Long['DEPVAR_1']).astype(int) # 提取y值 y = ATUS_data_LA_2020_Long['y'].values验证样本-备选方案结构:确保每个
custom_id对应的行数等于备选方案数量(这里是4行),避免样本行数异常导致的结构错误:sample_counts = ATUS_data_LA_2020_Long['custom_id'].value_counts() # 输出行数不等于4的样本 print(sample_counts[sample_counts != 4])若存在异常样本,检查
wide_to_long转换参数,比如alt_list是否完整、sep是否匹配宽格式列名的分隔规则。简化y的维度处理:xlogit本身支持一维数组的y输入,无需额外
ravel()操作,核心问题是y的取值逻辑错误,而非维度问题。
内容的提问来源于stack exchange,提问作者Catalina V
相关产品推荐
相关产品推荐

