OSCR

Patent license prediction using deep survival analysis: A comparative study.

Code ↔ Paper

11 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 11 matches
  1. [1] § Methods › Model architectures ↔ src/train_cure.py, lines 132–251 · score 0.92 · log hazard ratio, baseline hazard network, Cox linear predictor, licensability predictor, ReLU, Cox cure rate
  2. [2] § Methods › Training procedure ↔ src/train_cure.py, lines 411–541 · score 0.83 · learning rate scheduling, ReduceLROnPlateau, weight decay, Cox Cure, Adam, patience
  3. [3] § Methods › Training procedure ↔ src/train_deepsurv.py, lines 266–372 · score 0.79 · ReduceLROnPlateau, weight decay, Adam, patience, DeepSurv, clipping
  4. [4] § Methods › Model architectures ↔ src/train_cure.py, lines 132–251 · score 0.75 · log hazard ratio, Cox linear predictor, licensability predictor, baseline hazard, encoder, h0
  5. [5] § Methods › Model architectures ↔ src/train_cure.py, lines 1–32 · score 0.74 · cure fraction, modeling components, neural network, Cox cure rate, proportional hazards, baseline
  6. [6] § Related works › Deep survival analysis ↔ src/train_deepsurv.py, lines 1–34 · score 0.65 · Cox proportional hazards, neural networks, medical, DeepSurv, risks, prediction
  7. [7] § Methods › Model architectures ↔ src/train_cox.py, lines 28–152 · score 0.60 · backward citation, classical Cox, text embeddings, CPC
  8. [8] § Methods › Model architectures ↔ src/train_deepsurv.py, lines 1–34 · score 0.58 · deep neural network, Cox proportional hazards, DeepSurv, prediction, modeling
  9. [9] § Methods › Model architectures ↔ src/train_dnn.py, lines 64–160 · score 0.58 · ReLU, activations, dropout, layers, DNN, backward
  10. [10] § Related works › Deep survival analysis ↔ src/train_cure.py, lines 1–32 · score 0.56 · models assume, cure rate models, susceptible, population, event, baselines
  11. [11] § Methods › Training procedure ↔ src/train_cure.py, lines 75–125 · score 0.54 · trapezoidal rule, baseline hazard, cumulative, training

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 650 lines · 22 KB · MIT · 6 matches

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Cox Cure Rate Model Training
  5. This script trains a Cox proportional hazards model with cure fraction (cure rate model).
  6. The model assumes that a portion of the population will never experience the event (cured),
  7. while the remaining population follows a Cox proportional hazards model.
  8. Model Components:
  9. 1. Cure Fraction: P(cured) = 1 - p(X) where p(X) is the probability of being susceptible
  10. 2. Survival for Susceptible: S(t|X, not cured) follows Cox proportional hazards
  11. 3. Baseline Hazard: Modeled directly using a neural network
  12. Key Features:
  13. - Semi-parametric approach: parametric cure fraction + neural baseline hazard
  14. - Numerical integration for cumulative hazard calculation
  15. - Complex likelihood combining cured and susceptible populations
  16. """
  17. import argparse
  18. import torch
  19. import pandas as pd
  20. import numpy as np
  21. from torch import nn
  22. from torch.utils.data import Dataset, DataLoader
  23. from torch.optim import Adam
  24. from torch.optim.lr_scheduler import ReduceLROnPlateau, LambdaLR
  25. from datetime import datetime
  26. from pathlib import Path
  27. from utils import setup_logging, load_preprocessed_data, save_json, custom_collate_fn
  28. # ============================================================
  29. # Baseline Hazard Network
  30. # ============================================================
  31. class BaselineHazardNet(nn.Module):
  32. """
  33. Neural network to directly model baseline hazard function h₀(t).
  34. The baseline hazard is constrained to be non-negative using Softplus activation.
  35. """
  36. def __init__(self, hidden_dim=64):
  37. super().__init__()
  38. self.net = nn.Sequential(
  39. nn.Linear(1, hidden_dim),
  40. nn.ReLU(),
  41. nn.Linear(hidden_dim, hidden_dim // 2),
  42. nn.ReLU(),
  43. nn.Linear(hidden_dim // 2, 1),
  44. nn.Softplus() # Non-negative constraint
  45. )
  46. def forward(self, t):
  47. """
  48. Args:
  49. t: Time tensor [batch_size] or [batch_size, 1]
  50. Returns:
  51. Baseline hazard h₀(t) [batch_size]
  52. """
  53. if t.dim() == 1:
  54. t = t.unsqueeze(1)
  55. hazard = self.net(t)
  56. return hazard.squeeze(1)
  57. # ============================================================
  58. # Numerical Integration Utility
  59. # ============================================================
  60. def numerical_integration_trapezoid(hazard_net, t_end, n_steps=100):
  61. """
  62. Compute cumulative hazard function using trapezoidal rule.
  63. Integrates h₀(t) from 0 to t_end to get cumulative hazard Λ₀(t).
  64. Args:
  65. hazard_net: Baseline hazard network
  66. t_end: Integration upper limit (tensor) [batch_size]
  67. n_steps: Number of integration steps
  68. Returns:
  69. Cumulative hazard Λ₀(t) [batch_size]
  70. """
  71. device = t_end.device
  72. batch_size = t_end.shape[0]
  73. # Determine step size based on maximum t_end
  74. t_max = torch.max(t_end)
  75. dt = t_max / n_steps
  76. # Create integration points [n_steps+1, batch_size]
  77. t_points = torch.arange(0, n_steps + 1, device=device, dtype=torch.float32) * dt
  78. t_points = t_points.unsqueeze(1).expand(-1, batch_size)
  79. # Clip at each sample's t_end
  80. t_end_expanded = t_end.unsqueeze(0).expand(n_steps + 1, -1)
  81. t_points = torch.min(t_points, t_end_expanded)
  82. # Evaluate hazard function
  83. t_flat = t_points.flatten()
  84. hazard_values = hazard_net(t_flat)
  85. hazard_values = hazard_values.view(n_steps + 1, batch_size)
  86. # Trapezoidal rule: ∫f(x)dx ≈ Σ[f(x_i) + f(x_{i+1})] * dx/2
  87. cumulative_hazard = torch.zeros(batch_size, device=device)
  88. for i in range(batch_size):
  89. t_sample = t_end[i]
  90. n_steps_sample = int((t_sample / dt).item())
  91. n_steps_sample = min(n_steps_sample, n_steps)
  92. if n_steps_sample > 0:
  93. dt_sample = t_sample / n_steps_sample
  94. h_values = hazard_values[:n_steps_sample+1, i]
  95. # Apply trapezoidal rule
  96. integral = torch.sum(h_values[:-1] + h_values[1:]) * dt_sample / 2
  97. cumulative_hazard[i] = integral
  98. return cumulative_hazard
  99. # ============================================================
  100. # Model Definition
  101. # ============================================================
  102. class CoxCureModel(nn.Module):
  103. """
  104. Semi-parametric Cox Cure Rate Model.
  105. Architecture:
  106. 1. Shared feature encoder
  107. 2. Cure fraction predictor: P(susceptible to licensing)
  108. 3. Cox linear predictor: log hazard ratio
  109. 4. Baseline hazard network: h₀(t)
  110. """
  111. def __init__(self, emb_dim=768, cpc_vocab_size=129, app_vocab_size=207499,
  112. cpc_emb_dim=16, app_emb_dim=256, cpc_pad_idx=0, app_pad_idx=0):
  113. super().__init__()
  114. self.cpc_pad_idx = cpc_pad_idx
  115. self.app_pad_idx = app_pad_idx
  116. # Embedding layers
  117. self.cpc_emb = nn.EmbeddingBag(
  118. cpc_vocab_size + 1, cpc_emb_dim, mode='mean', padding_idx=cpc_pad_idx
  119. )
  120. self.app_emb = nn.EmbeddingBag(
  121. app_vocab_size + 1, app_emb_dim, mode='mean', padding_idx=app_pad_idx
  122. )
  123. # Shared feature encoder
  124. feature_dim = emb_dim + cpc_emb_dim + app_emb_dim + 2 # 1042
  125. self.feature_encoder = nn.Sequential(
  126. nn.Linear(feature_dim, 1024),
  127. nn.ReLU(),
  128. nn.Dropout(0.3),
  129. nn.Linear(1024, 512),
  130. nn.ReLU(),
  131. nn.Dropout(0.3)
  132. )
  133. # Cure fraction predictor (licensability predictor)
  134. self.licensability_predictor = nn.Sequential(
  135. nn.Linear(512, 256),
  136. nn.ReLU(),
  137. nn.Dropout(0.3),
  138. nn.Linear(256, 128),
  139. nn.ReLU(),
  140. nn.Linear(128, 1),
  141. nn.Sigmoid() # P(susceptible to licensing) ∈ [0, 1]
  142. )
  143. # Cox linear predictor (log hazard ratio)
  144. self.cox_predictor = nn.Sequential(
  145. nn.Linear(512, 256),
  146. nn.ReLU(),
  147. nn.Dropout(0.3),
  148. nn.Linear(256, 128),
  149. nn.ReLU(),
  150. nn.Linear(128, 1) # β'X (unconstrained)
  151. )
  152. # Baseline hazard network
  153. self.baseline_hazard_net = BaselineHazardNet(hidden_dim=64)
  154. def forward(self, num_claims, backward_cites, embeddings, cpc_ids, app_ids):
  155. batch_size = embeddings.shape[0]
  156. device = embeddings.device
  157. # Process CPC codes
  158. if cpc_ids.dim() == 2:
  159. cpc_mask = (cpc_ids != self.cpc_pad_idx)
  160. if cpc_mask.any():
  161. flat_cpc = cpc_ids[cpc_mask]
  162. cpc_lengths = cpc_mask.sum(dim=1)
  163. cpc_offsets = torch.cat([
  164. torch.tensor([0], device=device),
  165. cpc_lengths.cumsum(dim=0)[:-1]
  166. ])
  167. cpc_vec = self.cpc_emb(flat_cpc, cpc_offsets)
  168. else:
  169. cpc_vec = torch.zeros(batch_size, self.cpc_emb.embedding_dim, device=device)
  170. else:
  171. if len(cpc_ids) > 0:
  172. offsets = torch.tensor([0], dtype=torch.long, device=device)
  173. cpc_vec = self.cpc_emb(cpc_ids, offsets)
  174. else:
  175. cpc_vec = torch.zeros(1, self.cpc_emb.embedding_dim, device=device)
  176. # Process applicants
  177. if app_ids.dim() == 2:
  178. app_mask = (app_ids != self.app_pad_idx)
  179. if app_mask.any():
  180. flat_app = app_ids[app_mask]
  181. app_lengths = app_mask.sum(dim=1)
  182. app_offsets = torch.cat([
  183. torch.tensor([0], device=device),
  184. app_lengths.cumsum(dim=0)[:-1]
  185. ])
  186. app_vec = self.app_emb(flat_app, app_offsets)
  187. else:
  188. app_vec = torch.zeros(batch_size, self.app_emb.embedding_dim, device=device)
  189. else:
  190. if len(app_ids) > 0:
  191. offsets = torch.tensor([0], dtype=torch.long, device=device)
  192. app_vec = self.app_emb(app_ids, offsets)
  193. else:
  194. app_vec = torch.zeros(1, self.app_emb.embedding_dim, device=device)
  195. # Concatenate features
  196. x = torch.cat([
  197. embeddings, cpc_vec, app_vec,
  198. num_claims.unsqueeze(1),
  199. backward_cites.unsqueeze(1)
  200. ], dim=1)
  201. # Shared encoding
  202. encoded = self.feature_encoder(x)
  203. # Two outputs
  204. p_licensable = self.licensability_predictor(encoded).squeeze(1)
  205. cox_linear = self.cox_predictor(encoded).squeeze(1)
  206. return p_licensable, cox_linear
  207. # ============================================================
  208. # Dataset Definition
  209. # ============================================================
  210. class CureDataset(Dataset):
  211. """Dataset for Cox Cure Rate Model."""
  212. def __init__(self, df, max_cpc_len=10, max_app_len=5):
  213. self.df = df.reset_index(drop=True)
  214. self.max_cpc_len = max_cpc_len
  215. self.max_app_len = max_app_len
  216. self._prepare()
  217. def _prepare(self):
  218. self.num_claims = torch.tensor(
  219. self.df['num_claims_scaled'].values, dtype=torch.float32
  220. )
  221. self.backward_cites = torch.tensor(
  222. self.df['backward_citation_count_scaled'].values, dtype=torch.float32
  223. )
  224. # Text embeddings
  225. emb_cols = [f'text_emb_{i}_scaled' for i in range(768)]
  226. embeddings_data = []
  227. for col in emb_cols:
  228. if col in self.df.columns:
  229. embeddings_data.append(self.df[col].values)
  230. else:
  231. embeddings_data.append(np.zeros(len(self.df)))
  232. self.embeddings = np.column_stack(embeddings_data).astype(np.float32)
  233. # CPC codes
  234. self.cpc_ids = []
  235. for idx in range(len(self.df)):
  236. cpc_ids_str = self.df.iloc[idx]['cpc_ids']
  237. if isinstance(cpc_ids_str, str) and cpc_ids_str:
  238. cpc_id_list = [int(x) for x in cpc_ids_str.split(',') if x.strip()]
  239. cpc_id_list = list(dict.fromkeys(cpc_id_list))
  240. else:
  241. cpc_id_list = []
  242. cpc_id_list = cpc_id_list[:self.max_cpc_len]
  243. self.cpc_ids.append(torch.tensor(cpc_id_list, dtype=torch.long))
  244. # Applicant IDs
  245. self.applicant_ids = []
  246. for idx in range(len(self.df)):
  247. app_ids_str = self.df.iloc[idx]['app_ids']
  248. if isinstance(app_ids_str, str) and app_ids_str:
  249. app_id_list = [int(x) for x in app_ids_str.split(',') if x.strip()]
  250. app_id_list = list(dict.fromkeys(app_id_list))
  251. else:
  252. app_id_list = []
  253. app_id_list = app_id_list[:self.max_app_len]
  254. self.applicant_ids.append(torch.tensor(app_id_list, dtype=torch.long))
  255. # Survival data
  256. self.t_normalized = torch.tensor(self.df['t_normalized'].values, dtype=torch.float32)
  257. self.s = torch.tensor(self.df['s'].values, dtype=torch.float32)
  258. def __len__(self):
  259. return len(self.df)
  260. def __getitem__(self, idx):
  261. return (
  262. self.num_claims[idx],
  263. self.backward_cites[idx],
  264. torch.tensor(self.embeddings[idx], dtype=torch.float32),
  265. self.cpc_ids[idx],
  266. self.applicant_ids[idx],
  267. self.t_normalized[idx],
  268. self.s[idx]
  269. )
  270. # ============================================================
  271. # Loss Function
  272. # ============================================================
  273. def cox_cure_rate_loss(p_licensable, cox_linear, t_normalized, s, baseline_hazard_net):
  274. """
  275. Cox Cure Rate Model loss function.
  276. The likelihood combines two populations:
  277. 1. Cured (never licensed): probability (1 - p)
  278. 2. Susceptible (may be licensed): probability p, follows Cox model
  279. For event (s=1):
  280. L = p × h(t|X) × S(t|X)
  281. For censoring (s=0):
  282. L = p × S(t|X) + (1-p)
  283. where:
  284. h(t|X) = h₀(t) × exp(β'X) : hazard function
  285. S(t|X) = exp(-Λ₀(t) × exp(β'X)) : survival function
  286. Λ₀(t) = ∫₀ᵗ h₀(u)du : cumulative baseline hazard
  287. Args:
  288. p_licensable: Probability of being susceptible [batch_size]
  289. cox_linear: Cox linear predictor β'X [batch_size]
  290. t_normalized: Normalized time [batch_size]
  291. s: Event indicator [batch_size]
  292. baseline_hazard_net: Baseline hazard network
  293. Returns:
  294. Negative log likelihood
  295. """
  296. # Numerical stability
  297. p_licensable = torch.clamp(p_licensable, min=1e-8, max=1-1e-8)
  298. cox_linear = torch.clamp(cox_linear, min=-10, max=10)
  299. t_normalized = torch.clamp(t_normalized, min=1e-6, max=10.0)
  300. # Baseline hazard function
  301. hazard_0 = baseline_hazard_net(t_normalized) # h₀(t)
  302. # Cumulative baseline hazard via numerical integration
  303. cum_hazard_0 = numerical_integration_trapezoid(
  304. baseline_hazard_net, t_normalized, n_steps=50
  305. ) # Λ₀(t)
  306. # Clamp for numerical stability
  307. hazard_0 = torch.clamp(hazard_0, min=1e-8, max=100.0)
  308. cum_hazard_0 = torch.clamp(cum_hazard_0, min=1e-8, max=100.0)
  309. # Cox components
  310. exp_cox = torch.exp(cox_linear)
  311. h_t = hazard_0 * exp_cox # h(t|X) = h₀(t) × exp(β'X)
  312. S_t = torch.exp(-cum_hazard_0 * exp_cox) # S(t|X) = exp(-Λ₀(t) × exp(β'X))
  313. # Cure Rate Model likelihood
  314. # Event: p × h(t|X) × S(t|X)
  315. event_likelihood = s * p_licensable * h_t * S_t
  316. # Censoring: p × S(t|X) + (1-p)
  317. censoring_likelihood = (1-s) * (p_licensable * S_t + (1-p_licensable))
  318. # Total likelihood
  319. total_likelihood = event_likelihood + censoring_likelihood
  320. # Negative log likelihood
  321. neg_log_likelihood = -torch.log(total_likelihood + 1e-8)
  322. loss = neg_log_likelihood.mean()
  323. return loss
  324. # ============================================================
  325. # Training Function
  326. # ============================================================
  327. def warmup_lambda(epoch, warmup_epochs=5):
  328. """Learning rate warmup schedule."""
  329. if epoch < warmup_epochs:
  330. return (epoch + 1) / warmup_epochs
  331. return 1.0
  332. def train_model(model, train_loader, val_loader, device, config, logger):
  333. """Train Cox Cure Rate Model."""
  334. optimizer = Adam(
  335. model.parameters(),
  336. lr=config['lr'],
  337. weight_decay=config['weight_decay']
  338. )
  339. # Warmup + ReduceLROnPlateau
  340. warmup_scheduler = LambdaLR(
  341. optimizer,
  342. lr_lambda=lambda epoch: warmup_lambda(epoch, warmup_epochs=5)
  343. )
  344. main_scheduler = ReduceLROnPlateau(
  345. optimizer, mode='min', factor=0.5, patience=3, min_lr=1e-7
  346. )
  347. best_loss = float('inf')
  348. patience = 0
  349. training_history = []
  350. warmup_complete = False
  351. for epoch in range(config['epochs']):
  352. # Training
  353. model.train()
  354. total_loss = 0
  355. batch_count = 0
  356. for batch_idx, batch in enumerate(train_loader):
  357. optimizer.zero_grad()
  358. num_claims, backward_cites, embeddings, cpc_ids, app_ids, t_normalized, s = [
  359. x.to(device) for x in batch
  360. ]
  361. # Forward pass
  362. p_licensable, cox_linear = model(
  363. num_claims, backward_cites, embeddings, cpc_ids, app_ids
  364. )
  365. # Loss calculation
  366. loss = cox_cure_rate_loss(
  367. p_licensable, cox_linear, t_normalized, s,
  368. model.baseline_hazard_net
  369. )
  370. if torch.isnan(loss) or torch.isinf(loss):
  371. logger.warning(f"NaN/Inf loss at epoch {epoch+1}, batch {batch_idx+1}")
  372. continue
  373. # Backward pass
  374. loss.backward()
  375. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
  376. optimizer.step()
  377. total_loss += loss.item()
  378. batch_count += 1
  379. if batch_count == 0:
  380. continue
  381. avg_loss = total_loss / batch_count
  382. # Validation
  383. model.eval()
  384. with torch.no_grad():
  385. val_loss = 0
  386. val_batch_count = 0
  387. for batch in val_loader:
  388. num_claims, backward_cites, embeddings, cpc_ids, app_ids, t_normalized, s = [
  389. x.to(device) for x in batch
  390. ]
  391. p_licensable, cox_linear = model(
  392. num_claims, backward_cites, embeddings, cpc_ids, app_ids
  393. )
  394. loss = cox_cure_rate_loss(
  395. p_licensable, cox_linear, t_normalized, s,
  396. model.baseline_hazard_net
  397. )
  398. if not (torch.isnan(loss) or torch.isinf(loss)):
  399. val_loss += loss.item()
  400. val_batch_count += 1
  401. if val_batch_count == 0:
  402. val_loss = float('inf')
  403. else:
  404. val_loss /= val_batch_count
  405. training_history.append({
  406. 'epoch': epoch + 1,
  407. 'train_loss': float(avg_loss),
  408. 'val_loss': float(val_loss),
  409. 'learning_rate': float(optimizer.param_groups[0]['lr'])
  410. })
  411. logger.info(
  412. f"Epoch {epoch+1}/{config['epochs']} | "
  413. f"Train Loss: {avg_loss:.6f} | Val Loss: {val_loss:.6f}"
  414. )
  415. # Learning rate scheduling
  416. if epoch < 5:
  417. warmup_scheduler.step()
  418. else:
  419. if not warmup_complete:
  420. logger.info("Warmup complete, switching to ReduceLROnPlateau")
  421. warmup_complete = True
  422. main_scheduler.step(val_loss)
  423. # Early stopping
  424. if val_loss < best_loss:
  425. best_loss = val_loss
  426. patience = 0
  427. torch.save({
  428. 'epoch': epoch,
  429. 'model_state_dict': model.state_dict(),
  430. 'optimizer_state_dict': optimizer.state_dict(),
  431. 'loss': best_loss
  432. }, config['model_path'])
  433. logger.info(f" New best model saved (val_loss={best_loss:.6f})")
  434. else:
  435. patience += 1
  436. if patience >= config['early_stop']:
  437. logger.info("Early stopping triggered")
  438. break
  439. return {
  440. 'best_val_loss': float(best_loss),
  441. 'training_history': training_history
  442. }
  443. # ============================================================
  444. # Main Execution
  445. # ============================================================
  446. def main():
  447. """Main execution function."""
  448. parser = argparse.ArgumentParser(
  449. description='Train Cox Cure Rate Model'
  450. )
  451. parser.add_argument('--data_dir', type=str, required=True)
  452. parser.add_argument('--model_path', type=str, required=True)
  453. parser.add_argument('--results_path', type=str, required=True)
  454. parser.add_argument('--train_start', type=int, required=True)
  455. parser.add_argument('--train_end', type=int, required=True)
  456. parser.add_argument('--val_start', type=int, required=True)
  457. parser.add_argument('--val_end', type=int, required=True)
  458. parser.add_argument('--batch_size', type=int, default=256)
  459. parser.add_argument('--epochs', type=int, default=50)
  460. parser.add_argument('--lr', type=float, default=1e-4)
  461. parser.add_argument('--weight_decay', type=float, default=1e-4)
  462. parser.add_argument('--early_stop', type=int, default=10)
  463. parser.add_argument('--log_dir', type=str, default='logs')
  464. args = parser.parse_args()
  465. # Setup logging
  466. logger = setup_logging(log_dir=args.log_dir)
  467. logger.info("=== Cox Cure Rate Model Training ===")
  468. config = vars(args)
  469. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  470. logger.info(f"Device: {device}")
  471. # GPU memory clear
  472. if torch.cuda.is_available():
  473. torch.cuda.empty_cache()
  474. torch.cuda.synchronize()
  475. logger.info(f"GPU: {torch.cuda.get_device_name()}")
  476. # Create output directories
  477. Path(config['model_path']).parent.mkdir(parents=True, exist_ok=True)
  478. # Load data
  479. logger.info("\n=== Data Loading ===")
  480. train_df = load_preprocessed_data(
  481. config['data_dir'], config['train_start'], config['train_end'], logger
  482. )
  483. val_df = load_preprocessed_data(
  484. config['data_dir'], config['val_start'], config['val_end'], logger
  485. )
  486. # Prepare datasets
  487. logger.info("\n=== Dataset Preparation ===")
  488. train_ds = CureDataset(train_df)
  489. val_ds = CureDataset(val_df)
  490. train_loader = DataLoader(
  491. train_ds, batch_size=config['batch_size'], shuffle=True,
  492. drop_last=True, collate_fn=custom_collate_fn
  493. )
  494. val_loader = DataLoader(
  495. val_ds, batch_size=config['batch_size'], shuffle=False,
  496. collate_fn=custom_collate_fn
  497. )
  498. # Initialize model
  499. logger.info("\n=== Model Initialization ===")
  500. model = CoxCureModel(
  501. cpc_vocab_size=129,
  502. app_vocab_size=207499,
  503. cpc_pad_idx=0,
  504. app_pad_idx=0
  505. ).to(device)
  506. total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  507. logger.info(f"Trainable parameters: {total_params:,}")
  508. # Train
  509. logger.info("\n=== Training ===")
  510. start_time = datetime.now()
  511. try:
  512. result = train_model(model, train_loader, val_loader, device, config, logger)
  513. result['model_type'] = 'cox_cure'
  514. result['n_train_samples'] = len(train_df)
  515. result['n_val_samples'] = len(val_df)
  516. save_json(result, config['results_path'])
  517. end_time = datetime.now()
  518. duration = end_time - start_time
  519. logger.info("\n=== Training Complete ===")
  520. logger.info(f"Duration: {duration}")
  521. logger.info(f"Best validation loss: {result['best_val_loss']:.6f}")
  522. logger.info(f"Model saved: {config['model_path']}")
  523. except Exception as e:
  524. logger.error(f"Training error: {e}")
  525. import traceback
  526. logger.error(f"Traceback:\n{traceback.format_exc()}")
  527. raise
  528. if __name__ == '__main__':
  529. main()

train_cure.py at commit 403482f, under MIT · at the source

Overview

Authors: Takao Arai1, Hiroyasu Inoue1,2
ORCID iDs: Takao Arai
  1. Graduate School of Information Science, University of Hyogo, Kobe, Hyogo, Japan
  2. Center for Computational Science, RIKEN, Kobe, Hyogo, Japan
Journal: PloS one, volume 21, issue 9, article e0355826
Dates: received 25 January 2026; accepted 22 July 2026; published online 9 September 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pone.0355826 · PMID 42715259 · PMCID PMC13557344 · OpenAlex W7212070465
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), clinical / translational (subfield)
Methods: Connectivity, Machine learning, Statistics
MeSH: Deep Learning*, Licensure*, Patents as Topic*, Humans, Neural Networks, Computer, Prediction Algorithms, Predictive Learning Models, Proportional Hazards Models, Survival Analysis, United States (* major topic)
Topic: Intellectual Property and Patents (Management of Technology and Innovation, Business, Management and Accounting), according to OpenAlex
Funding: Asahi Glass Foundation; Japan Society for the Promotion of Science (23K20626, 25K01454, 24K00247, 26K00349, JP26K22092, 24K01108, 23K25520)
Citations: not cited yet (Europe PMC); 31 references in the paper

Abstract

Objective: We evaluate deep survival analysis frameworks for patent licensing prediction, systematically comparing cure rate models against standard approaches and quantifying the benefit of temporal modeling over static classification to address unresolved methodological questions following recent applications of neural survival models to patent contexts. Methods: We conducted experimental validation on 624,129 United States Patent and Trademark Office (USPTO) patents (2016–2017), comparing classical Cox regression, deep neural network baseline, DeepSurv (neural Cox proportional hazards), and Cox cure rate models. Performance was evaluated using metrics across 1-year, 3-year, and 5-year prediction horizons, with statistical significance assessed through patent-level bootstrap resampling (B = 1,000). Results: All deep learning approaches achieve high performance ( % 89.8–91.9%), substantially outperforming classical Cox regression (70.6–72.3%). Among neural architectures, DeepSurv—a standard neural Cox proportional hazards model—offers the optimal balance of simplicity and performance. More complex cure rate extensions provided no clear additional benefit over standard DeepSurv within the scope of this study: although bootstrap resampling detected a small but statistically significant difference (0.70 percentage points), this gap is practically negligible for patent screening, suggesting that explicit population heterogeneity modeling offers limited practical gains when deep feature learning is employed. Survival modeling provides statistically detectable but modest gains over static binary classification ( % differences of 0.5–1.6 percentage points), indicating that the primary value stems from capturing complex patent characteristics rather than explicit temporal modeling. Conclusion: This study provides, to the best of our knowledge, the first systematic evaluation of cure rate models and temporal modeling benefits for patent licensing prediction, demonstrating that architectural simplicity (DeepSurv) achieves near-optimal performance ( % 91%) when deep feature learning is prioritized. The findings offer actionable guidance for patent portfolio management: invest in feature learning infrastructure rather than architectural sophistication

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 11 matches between paragraphs and lines of code.

takaoarai/PatentLicensePrediction

License: MIT
State: the link answers, verified on 26 September 2026
Evidence: files inventoried
Commit: 403482fccbc271ccd2f8e6f6c8e2df9fcec7fa10, 11 February 2026
Languages: Python (8)
Size: 11 files, 8 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: pandas (7 files), NumPy (6 files), PyTorch (5 files), Hugging Face Transformers (1 file)
Availability: 1 check, the latest on 26 September 2026: the link answers
  • 26 September 2026: the link answers
10 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 8 scripts, each with its path and the digest of its content;
  • 11 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability

All data used in this study are publicly available. The USPTO Patent Assignment Dataset was obtained from https://www.uspto.gov/ip-policy/economic-research/research-datasets/patent-assignment-dataset, and Google Patents Public Datasets from Google BigQuery (https://console.cloud.google.com/marketplace/product/google_patents_public_datasets/google-patents-public-data). The authors had no special access privileges. Analysis code is available at https://github.com/takaoarai/PatentLicensePrediction.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 3, 28 September 2026

  • Funding: added Asahi Glass Foundation; Japan Society for the Promotion of Science: 23K20626, 25K01454, 24K00247, 26K00349, JP26K22092, 24K01108, 23K25520

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 10 MeSH terms, 27 references.

Cite

This paper

Arai, T., & Inoue, H. (2026). Patent license prediction using deep survival analysis: A comparative study. PloS one, 21(9), e0355826. https://doi.org/10.1371/journal.pone.0355826

BibTeX

@article{arai2026patent,
author = {Arai, Takao and Inoue, Hiroyasu},
title = {{Patent license prediction using deep survival analysis: A comparative study}},
journal = {PloS one},
year = {2026},
month = sep,
volume = {21},
number = {9},
pages = {e0355826},
publisher = {PLOS},
issn = {1932-6203},
doi = {10.1371/journal.pone.0355826},
url = {https://doi.org/10.1371/journal.pone.0355826},
pmid = {42715259},
pmcid = {PMC13557344}
}

RIS

TY - JOUR
AU - Arai, Takao
AU - Inoue, Hiroyasu
TI - Patent license prediction using deep survival analysis: A comparative study
T2 - PloS one
J2 - PLoS One
PY - 2026
DA - 2026/09/09
VL - 21
IS - 9
SP - e0355826
SN - 1932-6203
PB - PLOS
DO - 10.1371/journal.pone.0355826
UR - https://doi.org/10.1371/journal.pone.0355826
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pone.0355826",
"type": "article-journal",
"title": "Patent license prediction using deep survival analysis: A comparative study",
"container-title": "PloS one",
"author": [
{
"family": "Arai",
"given": "Takao"
},
{
"family": "Inoue",
"given": "Hiroyasu"
}
],
"container-title-short": "PLoS One",
"volume": "21",
"issue": "9",
"page": "e0355826",
"DOI": "10.1371/journal.pone.0355826",
"PMID": "42715259",
"PMCID": "PMC13557344",
"ISSN": "1932-6203",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pone.0355826",
"language": "en",
"issued": {
"date-parts": [
[
2026,
9,
9
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41591-026-04497-1 [code]
Health system learning enables generalist neuroimaging models.
Journal: Nature medicine
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[2] doi:10.1093/braincomms/fcag253 [code]
Disease detection and classification in temporal lobe epilepsy: step-wise versus simultaneous AI decision models in a multisite neuroimaging study.
Journal: Brain communications
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[3] doi:10.1016/j.isci.2026.116135 [code]
Predicting ICU in-hospital mortality from text-encoded structured EHR data using adaptive transformer layer fusion.
Journal: iScience
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[4] doi:10.1038/s43856-026-01606-6 [code]
Validation of remote multimodal AI screening for Parkinson disease across diverse settings.
Journal: Communications medicine
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[5] doi:10.1038/s41598-026-50791-w [code]
Hybrid Vi+ECNN framework for advanced ADHD diagnostic accuracy in medical imaging.
Journal: Scientific reports
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[6] doi:10.1016/j.patter.2026.101538 [code]
A multi-modal foundation model for brain disease diagnosis and medical imaging.
Journal: Patterns (New York, N.Y.)
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[7] doi:10.1038/s43856-026-01817-x [code]
Visual prompt engineering for multimodal and irregularly sampled medical data.
Journal: Communications medicine
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[8] doi:10.3389/fpsyt.2026.1803720 [code]
NeuroCon-AutismNet: a privacy-preserving multimodal framework toward autism screening via diffusion-regularized EEG biomarkers and empathy-aware multilingual dialogue.
Journal: Frontiers in psychiatry
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[9] doi:10.1038/s41746-026-02713-3 [code]
Learning like a radiologist: a medical vision-language model for radiological image analysis via curriculum learning.
Journal: NPJ digital medicine
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational
[10] doi:10.1038/s44387-026-00109-y [code]
SPARROW: subtyping Parkinson's disease with agentic reasoning and robust omics workflow.
Journal: NPJ artificial intelligence
In common: Hugging Face Transformers, PyTorch, pandas, 1 other tool, clinical / translational

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.