欢迎光临
我们一直在努力

颠覆“坚持就是成功”,编程计算项目成功概率与沉没成本,颠覆死磕思维,及时放弃低性价比目标。

🚀 颠覆"坚持就能成功":智能决策项目成功率计算器

 

📖 README.md

 

# 智能决策项目成功率计算器

 

## 🎯 项目简介

本项目基于智能决策理论,通过量化分析**项目成功概率**与**沉没成本**,帮助开发者/创业者做出理性决策:**何时坚持,何时及时止损**。

 

## 💡 核心理念

> "坚持不一定成功,及时放弃低性价比目标才是智慧"

 

## 📦 安装依赖

 

bash

 

pip install numpy matplotlib seaborn pandas

 

 

## 🚀 快速开始

 

bash

 

python project_decision.py –mode demo

 

python project_decision.py –mode interactive

 

 

## 📁 项目结构

 

smart_decision/

 

├── project_decision.py # 主程序入口

 

├── core/

 

│ ├── decision_engine.py # 决策引擎核心算法

 

│ ├── cost_calculator.py # 沉没成本计算器

 

│ └── probability_model.py # 成功概率模型

 

├── utils/

 

│ └── visualizer.py # 可视化模块

 

├── data/

 

│ └── historical_data.csv # 历史项目数据

 

└── README.md

 

 

## 📝 使用场景

– 软件开发项目是否继续投入?

– 创业项目ROI评估

– 个人学习计划止损判断

 

📱 实际应用场景描述

 

场景:全栈开发者的困境

 

李明是一名有5年经验的全栈开发者,正在开发一个SaaS产品。三个月过去了:

 

– ✅ 已投入:180小时开发时间 + 5000元云服务器费用 + 2000元第三方API费用

– ❓ 现状:核心功能完成60%,但遇到技术瓶颈,每周进度放缓

– 🤔 纠结:朋友说"坚持就能成功",但内心不确定是否值得继续

 

传统思维陷阱:

 

"都已经投入这么多了,放弃太可惜!" → 典型的沉没成本谬误

智能决策思维:

 

"基于当前数据和趋势,未来投入产出比是否合理?" → 理性决策

 

😣 引入痛点

 

痛点一:沉没成本绑架

 

开发者心理:

"我都写了3个月代码了,现在放弃之前的努力都白费了!"

→ 结果:在失败项目上越陷越深,错过更好的机会

 

痛点二:缺乏量化标准

 

传统判断方式:

"感觉差不多了" / "再试试看" / "别人都能做成"

→ 结果:凭感觉决策,没有数据支撑

 

痛点三:死磕思维作祟

 

典型心态:

"只要功夫深,铁杵磨成针"

→ 结果:在错误方向上消耗生命

 

痛点四:无法预测拐点

 

关键问题:

什么时候该坚持?什么时候该放弃?

→ 需要科学模型给出明确信号

 

🧠 核心逻辑讲解

 

核心公式体系

 

1️⃣ 成功概率动态模型

 

P(success) = Base_Rate × Technical_Fit × Market_Timing × Team_Capacity × Trend_Momentum

 

其中:

– Base_Rate: 同类项目历史成功率 (10%-40%)

– Technical_Fit: 技术匹配度 (0-1)

– Market_Timing: 市场时机评分 (0-1)  

– Team_Capacity: 团队能力匹配度 (0-1)

– Trend_Momentum: 近期进度动量 (0.5-1.5)

 

2️⃣ 沉没成本计算

 

Sunk_Cost = Time_Invested × Hourly_Rate + Actual_Expenses + Opportunity_Cost

 

Opportunity_Cost = Best_Alternative_Return × Remaining_Time

 

3️⃣ 期望价值决策

 

Expected_Value = P(success) × Expected_Reward – Total_Cost

 

Decision_Rule:

– EV > Threshold → 继续投资

– EV < Threshold → 及时止损

 

4️⃣ 止损信号触发条件

 

STOP_SIGNAL = (

    (P(success) < Min_Acceptable_Rate) OR 

    (EV < -Sunk_Cost × Risk_Tolerance) OR

    (Trend_Momentum < Momentum_Threshold)

)

 

💻 代码模块化实现

 

项目结构

 

smart_decision/

├── project_decision.py # 主程序入口

├── core/

│ ├── __init__.py

│ ├── decision_engine.py # 决策引擎核心

│ ├── cost_calculator.py # 成本计算模块

│ └── probability_model.py # 概率模型模块

├── utils/

│ ├── __init__.py

│ └── visualizer.py # 可视化模块

└── data/

    └── historical_data.json # 历史数据

 

1️⃣ 主程序入口 

"project_decision.py"

 

"""

智能决策项目成功率计算器

核心功能:量化分析项目成功概率与沉没成本,提供理性决策支持

"""

 

import argparse

import json

from datetime import datetime, timedelta

from typing import Dict, List, Tuple, Optional

import numpy as np

 

from core.decision_engine import DecisionEngine

from core.cost_calculator import CostCalculator

from core.probability_model import ProbabilityModel

from utils.visualizer import DecisionVisualizer

 

 

class ProjectDecisionSystem:

    """

    项目决策系统主类

    

    整合决策引擎、成本计算器和概率模型,

    提供完整的项目评估与决策支持功能。

    """

    

    def __init__(self):

        """初始化决策系统各组件"""

        self.decision_engine = DecisionEngine()

        self.cost_calculator = CostCalculator()

        self.probability_model = ProbabilityModel()

        self.visualizer = DecisionVisualizer()

        

        # 加载历史项目数据用于基准比较

        self.historical_data = self._load_historical_data()

        

    def _load_historical_data(self) -> Dict:

        """

        加载历史项目数据

        

        Returns:

            Dict: 包含历史项目统计信息

        """

        try:

            with open('data/historical_data.json', 'r', encoding='utf-8') as f:

                return json.load(f)

        except FileNotFoundError:

            # 返回默认历史数据

            return {

                "total_projects": 1000,

                "successful_projects": 280,

                "avg_development_time_months": 6.5,

                "avg_cost": 15000,

                "success_by_category": {

                    "web_app": 0.35,

                    "mobile_app": 0.28,

                    "saas_platform": 0.22,

                    "ai_ml": 0.18

                }

            }

    

    def evaluate_project(

        self,

        project_name: str,

        time_invested_hours: float,

        money_invested: float,

        completion_percentage: float,

        technical_fit: float,

        market_timing: float,

        team_capacity: float,

        expected_reward: float,

        hourly_rate: float = 50.0,

        project_type: str = "web_app",

        recent_progress_rates: List[float] = None

    ) -> Dict:

        """

        综合评估项目,提供决策建议

        

        Args:

            project_name: 项目名称

            time_invested_hours: 已投入时间(小时)

            money_invested: 已投入资金(元)

            completion_percentage: 完成百分比(0-100)

            technical_fit: 技术匹配度(0-1)

            market_timing: 市场时机评分(0-1)

            team_capacity: 团队能力匹配度(0-1)

            expected_reward: 预期收益(元)

            hourly_rate: 时薪(元/小时)

            project_type: 项目类型

            recent_progress_rates: 最近几周进度率列表

            

        Returns:

            Dict: 完整评估报告

        """

        

        print(f"\\n{'='*60}")

        print(f"📊 项目评估报告: {project_name}")

        print(f"{'='*60}")

        

        # Step 1: 计算沉没成本

        sunk_cost_result = self.cost_calculator.calculate_sunk_cost(

            time_invested_hours=time_invested_hours,

            money_invested=money_invested,

            hourly_rate=hourly_rate,

            opportunity_cost_rate=0.1, # 10%的机会成本率

            remaining_time_estimate=time_invested_hours * (100 – completion_percentage) / completion_percentage

        )

        

        print("\\n💰 【沉没成本分析】")

        print(f" 直接成本: ¥{sunk_cost_result['direct_cost']:.2f}")

        print(f" 机会成本: ¥{sunk_cost_result['opportunity_cost']:.2f}")

        print(f" 总沉没成本: ¥{sunk_cost_result['total_sunk_cost']:.2f}")

        

        # Step 2: 计算成功概率

        probability_result = self.probability_model.calculate_success_probability(

            base_rate=self.historical_data["success_by_category"].get(project_type, 0.28),

            technical_fit=technical_fit,

            market_timing=market_timing,

            team_capacity=team_capacity,

            trend_momentum=self._calculate_trend_momentum(recent_progress_rates),

            completion_percentage=completion_percentage

        )

        

        print("\\n🎯 【成功概率分析】")

        print(f" 基础成功率: {probability_result['base_rate']*100:.1f}%")

        print(f" 技术匹配度: {technical_fit*100:.1f}%")

        print(f" 市场时机: {market_timing*100:.1f}%")

        print(f" 团队能力: {team_capacity*100:.1f}%")

        print(f" 进度动量: {probability_result['trend_momentum']:.2f}")

        print(f" 🔮 综合成功概率: {probability_result['final_probability']*100:.1f}%")

        

        # Step 3: 计算期望价值与决策

        decision_result = self.decision_engine.make_decision(

            success_probability=probability_result['final_probability'],

            expected_reward=expected_reward,

            total_cost=sunk_cost_result['total_sunk_cost'],

            remaining_cost_estimate=sunk_cost_result['remaining_cost_estimate'],

            risk_tolerance=0.3 # 30%风险容忍度

        )

        

        print("\\n⚖️ 【决策分析】")

        print(f" 期望价值(EV): ¥{decision_result['expected_value']:.2f}")

        print(f" 总投资预估: ¥{decision_result['total_investment_estimate']:.2f}")

        print(f" 风险调整后回报: ¥{decision_result['risk_adjusted_return']:.2f}")

        print(f" 性价比指数: {decision_result['value_ratio']:.3f}")

        

        # Step 4: 生成决策建议

        recommendation = self._generate_recommendation(decision_result, probability_result)

        print(f"\\n📋 【决策建议】")

        print(f" {recommendation}")

        

        # Step 5: 可视化展示

        self.visualizer.plot_decision_analysis(

            project_name=project_name,

            sunk_cost=sunk_cost_result,

            probability_result=probability_result,

            decision_result=decision_result

        )

        

        # 汇总报告

        report = {

            "project_name": project_name,

            "timestamp": datetime.now().isoformat(),

            "sunk_cost_analysis": sunk_cost_result,

            "probability_analysis": probability_result,

            "decision_analysis": decision_result,

            "recommendation": recommendation,

            "should_continue": decision_result['should_continue']

        }

        

        return report

    

    def _calculate_trend_momentum(self, progress_rates: List[float]) -> float:

        """

        计算进度动量

        

        Args:

            progress_rates: 最近进度率列表

            

        Returns:

            float: 动量值(0.5-1.5)

        """

        if not progress_rates or len(progress_rates) < 2:

            return 1.0 # 默认正常动量

        

        # 计算加权平均动量

        weights = np.array([0.1, 0.15, 0.25, 0.5][:len(progress_rates)][::-1])

        momentum = np.average(progress_rates[-4:], weights=weights[:len(progress_rates)])

        

        # 归一化到0.5-1.5范围

        normalized_momentum = 0.5 + momentum * 1.0

        return min(max(normalized_momentum, 0.5), 1.5)

    

    def _generate_recommendation(self, decision_result: Dict, probability_result: Dict) -> str:

        """

        生成人性化决策建议

        

        Args:

            decision_result: 决策分析结果

            probability_result: 概率分析结果

            

        Returns:

            str: 建议文本

        """

        prob = probability_result['final_probability']

        ev = decision_result['expected_value']

        value_ratio = decision_result['value_ratio']

        

        if not decision_result['should_continue']:

            reasons = []

            if prob < 0.25:

                reasons.append("成功概率过低")

            if ev < -5000:

                reasons.append("期望价值为负")

            if value_ratio < 0.5:

                reasons.append("性价比严重不足")

            

            reason_text = "、".join(reasons) if reasons else "综合评估不达标"

            return f"🛑 【建议立即停止】{reason_text}。继续投入将造成更大损失。"

        

        elif prob < 0.45:

            return f"⚠️ 【谨慎考虑】成功概率({prob*100:.1f}%)偏低,建议重新评估项目方向或寻找突破点。"

        

        elif value_ratio < 1.0:

            return f"🔄 【优化后再决定】性价比指数({value_ratio:.2f})不足,建议优化技术方案或降低成本。"

        

        else:

            return f"✅ 【建议继续】各项指标良好,成功概率({prob*100:.1f}%),性价比({value_ratio:.2f})合理,可继续投入。"

 

 

def run_demo():

    """运行演示案例"""

    system = ProjectDecisionSystem()

    

    print("\\n" + "="*70)

    print("🚀 智能决策系统演示 – 颠覆'坚持就能成功'思维")

    print("="*70)

    

    # 案例1: SaaS项目 – 应该止损的情况

    print("\\n\\n【案例1】SaaS项目管理后台项目")

    print("-" * 50)

    result1 = system.evaluate_project(

        project_name="SaaS管理后台",

        time_invested_hours=180, # 3个月 * 60小时/月

        money_invested=7000, # 服务器+API费用

        completion_percentage=60,

        technical_fit=0.4, # 技术栈不够熟悉

        market_timing=0.3, # 市场已饱和

        team_capacity=0.5, # 团队经验不足

        expected_reward=50000, # 预期年收入5万

        hourly_rate=80, # 资深开发者时薪

        project_type="saas_platform",

        recent_progress_rates=[0.08, 0.06, 0.04, 0.03] # 进度持续下降

    )

    

    # 案例2: 工具类App – 应该继续的情况

    print("\\n\\n【案例2】效率工具类移动App")

    print("-" * 50)

    result2 = system.evaluate_project(

        project_name="效率工具App",

        time_invested_hours=120, # 2个月

        money_invested=3000,

        completion_percentage=40,

        technical_fit=0.85, # 技术栈熟练

        market_timing=0.75, # 市场需求旺盛

        team_capacity=0.8, # 团队能力强

        expected_reward=150000, # 预期年收入15万

        hourly_rate=60,

        project_type="mobile_app",

        recent_progress_rates=[0.12, 0.14, 0.13, 0.15] # 进度稳定上升

    )

    

    # 对比总结

    print("\\n\\n" + "="*70)

    print("📈 对比总结")

    print("="*70)

    print(f"\\nSaaS项目 – 成功概率: {result1['probability_analysis']['final_probability']*100:.1f}%, "

          f"建议: {'继续' if result1['should_continue'] else '止损'}")

    print(f"工具App – 成功概率: {result2['probability_analysis']['final_probability']*100:.1f}%, "

          f"建议: {'继续' if result2['should_continue'] else '止损'}")

    print("\\n💡 核心洞察: 不是所有坚持都有意义,理性决策胜过盲目死磕!")

 

 

def run_interactive():

    """运行交互式评估"""

    system = ProjectDecisionSystem()

    

    print("\\n" + "="*70)

    print("🎮 交互式项目评估")

    print("="*70)

    

    project_name = input("\\n请输入项目名称: ").strip() or "未命名项目"

    

    try:

        time_invested = float(input("已投入时间(小时): ") or "0")

        money_invested = float(input("已投入资金(元): ") or "0")

        completion = float(input("完成百分比(0-100): ") or "0")

        tech_fit = float(input("技术匹配度(0-1): ") or "0.5")

        market_timing = float(input("市场时机评分(0-1): ") or "0.5")

        team_cap = float(input("团队能力评分(0-1): ") or "0.5")

        expected_reward = float(input("预期收益(元): ") or "0")

        hourly_rate = float(input("时薪(元/小时): ") or "50")

        

        system.evaluate_project(

            project_name=project_name,

            time_invested_hours=time_invested,

            money_invested=money_invested,

            completion_percentage=completion,

            technical_fit=tech_fit,

            market_timing=market_timing,

            team_capacity=team_cap,

            expected_reward=expected_reward,

            hourly_rate=hourly_rate

        )

    except ValueError as e:

        print(f"❌ 输入错误: {e}")

 

 

def main():

    """主函数"""

    parser = argparse.ArgumentParser(description="智能决策项目成功率计算器")

    parser.add_argument('–mode', type=str, default='demo',

                       choices=['demo', 'interactive', 'batch'],

                       help='运行模式: demo(演示), interactive(交互), batch(批量)')

    

    args = parser.parse_args()

    

    if args.mode == 'demo':

        run_demo()

    elif args.mode == 'interactive':

        run_interactive()

    elif args.mode == 'batch':

        print("批量模式开发中…")

 

 

if __name__ == "__main__":

    main()

 

2️⃣ 决策引擎核心 

"core/decision_engine.py"

 

"""

决策引擎核心模块

负责整合概率分析和成本计算,做出最终决策

"""

 

from typing import Dict, Any

import numpy as np

 

 

class DecisionEngine:

    """

    决策引擎类

    

    基于期望价值理论和风险调整模型,

    提供项目继续/止损的决策建议。

    """

    

    def __init__(self):

        """初始化决策引擎参数"""

        # 决策阈值配置

        self.thresholds = {

            "min_success_rate": 0.25, # 最低可接受成功率

            "min_expected_value": -5000, # 最小期望价值

            "min_value_ratio": 0.5, # 最小性价比指数

            "risk_tolerance": 0.3 # 风险容忍度

        }

        

        # 历史基准数据

        self.benchmarks = {

            "avg_project_duration": 6.5, # 平均项目周期(月)

            "avg_roi": 2.5, # 平均投资回报率

            "success_confidence_level": 0.95 # 置信水平

        }

    

    def make_decision(

        self,

        success_probability: float,

        expected_reward: float,

        total_cost: float,

        remaining_cost_estimate: float,

        risk_tolerance: float = 0.3

    ) -> Dict[str, Any]:

        """

        核心决策函数

        

        使用期望价值理论结合风险调整,

        判断是否应该继续投资项目。

        

        Args:

            success_probability: 项目成功概率(0-1)

            expected_reward: 预期总收益(元)

            total_cost: 已投入总成本(元)

            remaining_cost_estimate: 剩余成本预估(元)

            risk_tolerance: 风险容忍度(0-1)

            

        Returns:

            Dict: 包含决策结果和详细分析

        """

        

        # 1. 计算期望价值 (Expected Value)

        # EV = P(成功) × 收益 – 总成本

        expected_value = (success_probability * expected_reward) – total_cost

        

        # 2. 计算风险调整期望价值

        # 考虑不确定性对期望值的折减

        risk_adjustment_factor = 1 – (1 – success_probability) * risk_tolerance

        risk_adjusted_ev = expected_value * risk_adjustment_factor

        

        # 3. 计算总投资预估

        total_investment_estimate = total_cost + remaining_cost_estimate

        

        # 4. 计算性价比指数

        # 衡量每投入1元能获得多少期望价值

        value_ratio = expected_value / total_investment_estimate if total_investment_estimate > 0 else 0

        

        # 5. 计算止损损失比

        # 停止项目的损失占已投入成本的比例

        stop_loss_ratio = total_cost / (total_cost + expected_reward) if (total_cost + expected_reward) > 0 else 1

        

        # 6. 综合决策判断

        should_continue = self._evaluate_continue_condition(

            success_probability=success_probability,

            expected_value=expected_value,

            value_ratio=value_ratio,

            stop_loss_ratio=stop_loss_ratio,

            risk_tolerance=risk_tolerance

        )

        

        # 7. 计算信心度

        confidence_score = self._calculate_confidence(

            success_probability=success_probability,

            expected_value=expected_value

        )

        

        return {

            "should_continue": should_continue,

            "expected_value": round(expected_value, 2),

            "risk_adjusted_ev": round(risk_adjusted_ev, 2),

            "total_investment_estimate": round(total_investment_estimate, 2),

            "value_ratio": round(value_ratio, 3),

            "stop_loss_ratio": round(stop_loss_ratio, 3),

            "confidence_score": round(confidence_score, 3),

            "risk_assessment": self._assess_risk(success_probability, expected_value),

            "decision_factors": self._identify_decision_factors(

                success_probability, expected_value, value_ratio

            )

        }

    

    def _evaluate_continue_condition(

        self,

        success_probability: float,

        expected_value: float,

        value_ratio: float,

        stop_loss_ratio: float,

        risk_tolerance: float

    ) -> bool:

        """

        评估是否满足继续投资的条件

        

        Returns:

            bool: True表示继续,False表示止损

        """

        

        # 硬性条件检查

        conditions = [

            success_probability >= self.thresholds["min_success_rate"],

            expected_value >= self.thresholds["min_expected_value"],

            value_ratio >= self.thresholds["min_value_ratio"]

        ]

        

        # 软性条件:止损损失是否在可接受范围内

        acceptable_stop_loss = stop_loss_ratio <= (1 – risk_tolerance * 0.5)

        

        # 综合判断:至少满足2个硬性条件且止损可接受

        hard_conditions_met = sum(conditions) >= 2

        

        return hard_conditions_met and acceptable_stop_loss

    

    def _calculate_confidence(

        self,

        success_probability: float,

        expected_value: float

    ) -> float:

        """

        计算决策信心度

        

        基于成功概率和期望价值的稳定性

        """

        # 使用sigmoid函数将概率映射到0-1的信心度

        prob_confidence = 1 / (1 + np.exp(-10 * (success_probability – 0.5)))

        

        # 价值稳定性置信度

        if expected_value > 0:

            value_confidence = min(expected_value / 10000, 1.0)

        else:

            value_confidence = max(0.1, 1 + expected_value / 10000)

        

        # 综合信心度

        return (prob_confidence + value_confidence) / 2

    

    def _assess_risk(

        self,

        success_probability: float,

        expected_value: float

    ) -> str:

        """

        风险评估

        

        Returns:

            str: 风险等级描述

        """

        if success_probability < 0.2 or expected_value < -10000:

            return "🔴 高风险 – 建议立即止损"

        elif success_probability < 0.4 or expected_value < 0:

            return "🟡 中风险 – 需谨慎考虑"

        elif success_probability < 0.6 or expected_value < 5000:

            return "🟢 低风险 – 可继续观察"

        else:

            return "🟢 极低风险 – 可积极投入"

    

    def _identify_decision_factors(

        self,

        success_probability: float,

        expected_value: float,

        value_ratio: float

    ) -> List[str]:

        """

        识别影响决策的关键因素

        

        Returns:

            List[str]: 关键因素列表

        """

        factors = []

        

        if success_probability < 0.3:

            factors.append("成功概率过低")

        if success_probability > 0.7:

            factors.append("成功概率较高")

            

        if expected_value < 0:

            factors.append("期望价值为负数")

        elif expected_value > 10000:

            factors.append("期望价值丰厚")

            

        if value_ratio < 0.5:

            factors.append("性价比不足")

        elif value_ratio > 1.5:

            factors.append("性价比优秀")

            

        return factors if factors else ["各项指标均衡"]

利用AI解决实际问题,如果你觉得这个工具好用,欢迎关注长安牧笛!

    

 

赞(0)
未经允许不得转载:171主机测评 » 颠覆“坚持就是成功”,编程计算项目成功概率与沉没成本,颠覆死磕思维,及时放弃低性价比目标。
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址