You need to enable JavaScript to run this app. OCaml使用逻辑回归时Lacaml未绑定错误及数据类型疑问
优惠活动
大模型
产品
解决方案
定价
更多

OCaml使用逻辑回归时Lacaml未绑定错误及数据类型疑问

OCaml 逻辑回归实现相关问题

我需要将逻辑回归作为黑盒用于正在解决的其他问题,在OCaml环境中使用逻辑回归功能,参考了公开的OCaml逻辑回归实现教学站点的示例。
我将站点中的如下代码做了少量修改(自定义了iris_features与iris_labels的定义),粘贴到名为logistic_regression.ml的文件中:

open Scanf
open Format
open Bigarray
open Lacaml.D

let log_reg ?(lambda=0.1) x y =
  (* [f_df] returns the value of the function to maximize and store
     its gradient in [g]. *)
  let f_df w g =
    let s = ref 0. in
    ignore(copy ~y:g w); (* g ← w *)
    scal (-. lambda) g;  (* g = -λ w *)
    for i = 0 to Array.length x - 1 do
      let yi = float y.(i) in
      let e = exp(-. yi *. dot w x.(i)) in
      s := !s +. log1p e;
      axpy g ~alpha:(yi *. e /. (1. +. e)) ~x:x.(i);
    done;
    -. !s -. 0.5 *. lambda *. dot w w
  in
  let w = Vec.make0 (Vec.dim x.(0)) in
  ignore(Lbfgs.F.max f_df w);
  w


let iris_features = [1 ; 2 ; 3] ;;
let iris_labels = 2 ;;

let proba w x y = 1. /. (1. +. exp(-. float y *. dot w x))
let () =
  let sol = log_reg iris_features iris_labels in
  printf "w = %a\n" Lacaml.Io.pp_fvec sol;
  let nwrongs = ref 0 in
  for i = 0 to Array.length iris_features - 1 do
    let p = proba sol iris_features.(i) iris_labels.(i) in
    printf "Label = %i prob = %g => %s\n" iris_labels.(i) p
      (if p > 0.5 then "correct" else (incr nwrongs; "wrong"))
  done;
  printf "Number of wrong labels: %i\n" !nwrongs

现存待解决问题

  • 编译代码时收到报错信息:Error: Unbound module Lacaml,已安装Lacaml、多次执行opam init,尝试添加-package = Lacaml编译参数仍未解决该问题。
  • 自行定义iris_features为int列表、iris_labels为int类型,不确定是否适配log_reg函数的输入要求:即log_reg函数要求的参数x是否为int列表、参数y是否为int类型?

内容的提问来源于stack exchange,提问作者Anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 02:15:03