从0开始机器学习--Day9--逻辑回归作业1.0

题目:假设你是一所大学的管理员,给出一份数据集,里面有每个学生第一次考试成绩、第二次考试成绩以及是否录取的数据,请建立一个逻辑回归模型用来预测学生的录取情况。

下面是我根据视频订正后的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.optimize as opt
from sklearn.metrics import classification_report

# 定义函数sigmoid,方便后续假设函数以sigmoid(z)表示
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# 定义代价函数
def computeCost (theta, X, y):
    predictions = sigmoid(X @ theta)  # 使用 @ 进行矩阵乘法
    first = np.multiply(-y, np.log(predictions))
    second = np.multiply((1 - y), np.log(1 - predictions))
    return np.sum(first - second) / len(X)  # 返回标量

# 梯度下降公式,这里只计算一个步长
def gradient(theta, X, y):
    return (1/len(X))*(X.T@(sigmoid(X@theta)-y))

# 预测函数
def predict(X, theta):
    probability = sigmoid(X@theta)
    return [1 if x >= 0.5 else 0 for x in probability]

data = pd.read_csv('ex2data1.txt', names = ['first-score', 'second-score', 'admitted'])

sns.set(context='notebook', style='whitegrid')
sns.lmplot(x='first-score', y='second-score', hue='admitted',   #定义数据子集的变量,绘制在图中
            data=data,
            height=6,
           fit_reg=False,  
           scatter_kws={"s": 50}
           )
plt.show()

data.insert(0, 'ONE', 1)

X = np.array(data.iloc[:, :-1].values)  # 特征矩阵 (100, 3)
y = np.array(data.iloc[:, -1].values)  # 将 y 转换为 (100,)

theta = np.zeros(3)

print(computeCost(theta, X, y))

print(gradient(theta, X, y))

print("X shape:", X.shape)  # 应该是 (m, n)
print("y shape:", y.shape)  # 应该是 (m, 1)
print("Initial theta shape:", theta.shape)  # 应为 (3, 1)
print("Theta (flattened):", theta.flatten())  # 保证在res中theta是一维数组

res = opt.minimize(fun=computeCost, x0=theta.flatten(), args=(X, y), method='Newton-CG', jac=gradient)

print(res)

last_theta=res.x
y_pred=predict(X, last_theta)
print(classification_report(y, y_pred))

coef = -(res.x/ ((res.x)[2])) #将result[0]中的每一个数除以result[0]中的第三个元素,然后取相反值
print(coef)

x = np.arange(130, step=0.1) #默认起点为0,终点为130,步长为0.1的数组
y = coef[0] + coef[1]*x

sns.set(context='notebook',style='whitegrid',palette='bright')
sns.lmplot(x='first-score', y='second-score', hue='admitted',   #定义数据子集的变量,绘制在图中
            data=data,
            height=6,
           fit_reg=False,  
           scatter_kws={"s": 50}

           )

plt.plot(x, y, 'grey') #plot为画图函数,plot(x变量,y变量,‘线条颜色和;类型’),设置线条颜色为灰色
plt.xlim(0, 130)  #设置x轴的范围
plt.ylim(0, 130) #设置y轴的范围
plt.title('Decision Boundary')  #设置标题
plt.show()

输出的数据散点图和算出决策边界后的图像如下:

原始数据录取情况散点图

带有决策边界,拟合好的图

输出如下:

0.6931471805599453
[ -0.1        -12.00921659 -11.26284221]
X shape: (100, 3)
y shape: (100,)
Initial theta shape: (3,)
Theta (flattened): [0. 0. 0.]
     fun: 0.20576462118328537
     jac: array([ 0.00121975, -0.00705683, -0.0064625 ])
 message: 'Optimization terminated successfully.'
    nfev: 71
    nhev: 0
     nit: 25
    njev: 160
  status: 0
 success: True
       x: array([-21.50746203,   0.17701971,   0.17190147])
              precision    recall  f1-score   support

           0       0.87      0.85      0.86        40
           1       0.90      0.92      0.91        60

    accuracy                           0.89       100
   macro avg       0.89      0.88      0.88       100
weighted avg       0.89      0.89      0.89       100

[125.1150549   -1.02977425  -1.        ]

进程已结束,退出代码0

在作业讲解视频中,如果使用的是跟视频一样的代码,读取特征方法get_X(df)的最后一句,return data.iloc[:, :-1].as_matrix(),用新版本的pandas包会报错('DataFrame' object has no attribute 'as_matrix'),因为新版本的pandas已经去除了as_matrix()方法,只需要把as_matrix()改为values即可。(小编用不一样的方法取值的输出也跟视频输出的值不一样,可能是库的问题)

第二次吴恩达机器学习作业逻辑回归作业总结:在此次作业中学习到了可以使用在视频中说的共轭梯度法来优化梯度下降中的参数,从而只需要计算一个步长而不需要进行完整的梯度下降。但本次作业中小编遇到了许多显示矩阵维度的问题,这说明在算法的计算过程中,矩阵运算的维度需要严格按照其运算规律,希望在以后的作业中能够在定义参数还有特征量等矩阵时能注意到这点,可以通过输出其维度的形式来排除错误以及确保报错是语法问题而不是定义问题。

作业改正参考视频:【作业讲解】编程作业2:逻辑回归+正则化(上)_哔哩哔哩_bilibili

<think>好的,我现在需要帮助用户使用IntelliJ IDEA社区版创建一个简易的机器学习欺诈检测系统,包括前后端代码,并展示代码结构。用户希望代码简洁,所以我要确保结构清晰,同时功能完整。 首先,我需要确定整个系统的架构。通常,这样的系统可能分为前端、后端和机器学习模型部分。前端负责展示界面,后端处理请求,模型进行预测。考虑到用户可能对技术栈不太熟悉,我应该选择常用的框架,比如Spring Boot作为后端,React或简单的HTML/JS作为前端,但为了简化,可能直接用Spring Boot的Thymeleaf模板引擎。不过用户要求代码简洁,所以可能前后端分离更合适,但需要快速实现的话,可能后端直接提供RESTAPI,前端用简单的HTML+JavaScript调用。 接下来是机器学习部分。需要选择一个简单的分类算法,比如逻辑回归或随机森林,使用Python的scikit-learn库训练模型,然后将模型保存为文件。但用户可能希望整个系统用Java,不过社区版IDEA可能更适合Java项目。不过Java的机器学习库不如Python丰富,所以可能需要用Python训练模型,然后Java调用。或者,使用Weka库,这是Java的机器学习库。为了简化,可能使用Weka直接在Java中训练模型。但欺诈检测可能需要实时预测,所以模型需要预先训练好,加载到后端中进行预测。 接下来考虑代码结构。后端使用Spring Boot,结构通常包括控制器、服务、模型层。前端可能是一个简单的HTML页面,通过AJAX调用后端API。机器学习模型需要集成到后端中,可能作为服务组件。可能的步骤: 1. 创建SpringBoot项目,添加必要的依赖(如Web,Thymeleaf,可能Weka或者集成Python模型)。 2. 训练一个简单的欺诈检测模型,保存为文件(比如使用Weka的序列化模型)。 3.后端代码:创建REST API接收交易数据,调用模型进行预测。 4.前端页面:表单输入交易信息,发送请求到后端,显示结果。如果使用Weka,需要处理模型加载和预测。或者,如果用户希望用Python训练模型,可能需要Java调用Python脚本,但这样会增加复杂度。所以可能使用Weka在Java中直接处理。现在,代码结构可能如下: -src/main/java- com.fraud.detection- controller(处理HTTP请求) - service(加载模型,进行预测)- model (数据传输对象,如Transaction) - src/main/resources -static (前端JS/CSS)- templates (HTML页面) -model (保存的Weka模型文件) 接下来编写各部分代码: 后端控制器:处理POST请求,接收交易数据,调用服务层进行预测,返回结果。 服务层:加载Weka模型,将传入的交易数据转换为Weka的实例,进行预测。 前端:简单的HTML表单,输入交易金额、类别等,通过JavaScript发送POST请求,显示结果。 但使用Weka可能需要添加依赖。在pom.xml中添加Weka的依赖:<dependency><groupId>nz.ac.waikato.cms.weka</groupId> <artifactId>weka-stable</artifactId><version>3.8.6</version></dependency> 然后训练模型,保存为model.model文件。但用户可能需要示例代码,所以可能需要生成一个简单的模型,或者在项目启动时训练一个模型。 但欺诈检测数据集通常包含交易特征,如金额、类别、时间、地点等。示例数据可能需要简化,比如amount, category, time_of_day等。例如,假设模型输入特征为:金额(数值)、类别(分类变量,如0,1,2)、时间(小时),输出是否为欺诈(01)。服务层加载模型,接收Transaction对象,构造Instance对象,使用模型预测。 现在,代码示例: 后端控制器: @RestController@RequestMapping("/api")public class FraudController{ private finalFraudDetectionService service; //依赖注入public FraudController(FraudDetectionService service) { this.service = service;} @PostMapping("/detect") publicResponseEntity<FraudResult> detectFraud(@RequestBody Transactiontransaction) {boolean isFraud= service.predict(transaction); returnResponseEntity.ok(new FraudResult(isFraud)); } }服务层: @Servicepublic class FraudDetectionService {private Classifier model; @PostConstruct publicvoid init() throwsException { model= (Classifier)SerializationHelper.read(getClass().getResourceAsStream("/model/weka_model.model"));} public booleanpredict(Transaction transaction) { //将transaction转为Weka InstanceInstance instance =new DenseInstance(4); //假设3个特征,可能还要调整 instance.setDataset(...);// 需要设置正确的数据集结构instance.setValue(0, transaction.getAmount());instance.setValue(1, transaction.getCategory()); instance.setValue(2, transaction.getTimeOfDay());double pred = model.classifyInstance(instance); returnpred == 1.0;} } 这里的问题是如何正确构建Weka的Instance,需要确保数据集结构与训练时一致。因此,在训练模型时,需要保存数据集结构,或者在服务层中重新创建正确的结构。 这可能会变得复杂,特别是对于分类变量。可能需要在服务层中硬编码属性信息,或者在训练时保存一个Arff头文件。 例如,在服务层初始化时,创建正确的Attributes: //在init方法中创建Attribute列表ArrayList<Attribute> attributes = newArrayList<>(); attributes.add(new Attribute("amount")); attributes.add(newAttribute("category",Arrays.asList("0", "1","2")));// 假设类别是0,1,2 attributes.add(new Attribute("time_of_day"));Attribute classAttribute =new Attribute("class", Arrays.asList("0", "1")); attributes.add(classAttribute); Instancesdataset = new Instances("transaction",attributes, 0); dataset.setClassIndex(3);// class是第4个属性然后在创建Instance时: Instance instance =new DenseInstance(4); instance.setValue(attributes.get(0),transaction.getAmount());instance.setValue(attributes.get(1), String.valueOf(transaction.getCategory()));instance.setValue(attributes.get(2), transaction.getTimeOfDay()); instance.setDataset(dataset); 这样可能更准确。但需要确保训练模型时的结构与服务层中的一致。 前端部分,可以是一个简单的HTML页面,使用Fetch API发送POST请求: <html><body><input type="number" id="amount" placeholder="Amount"> <inputtype="number"id="category"placeholder="Category (0,1,2)"><input type="number" id="time" placeholder="Timeof day (0-23)"><button onclick="detectFraud()">Check</button><div id="result"></div><script>function detectFraud() { constdata = {amount: parseFloat(document.getElementById(&#39;amount&#39;).value),category: parseInt(document.getElementById(&#39;category&#39;).value), timeOfDay: parseInt(document.getElementById(&#39;time&#39;).value)}; fetch(&#39;/api/detect&#39;,{ method:&#39;POST&#39;,headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },body: JSON.stringify(data)}) .then(response => response.json()) .then(result => {document.getElementById(&#39;result&#39;).innerText =result.fraud ?&#39;Fraudulent!&#39; : &#39;Legitimate&#39;; });} </script> </body> </html>但需要将HTML文件放在resources/static或templates目录下,并配置Spring Boot的静态资源处理。关于模型训练,用户可能需要示例代码来生成模型。可以使用Weka的API在Java中训练一个简单的模型,比如使用决策树或随机森林。例如: publicclass ModelTrainer{ public staticvoid main(String[]args) throws Exception{ //加载数据集Instances data =...; //加载训练数据data.setClassIndex(data.numAttributes() - 1); Classifierclassifier = new RandomTree(); classifier.buildClassifier(data);// 保存模型 SerializationHelper.write("src/main/resources/model/weka_model.model", classifier);} } 但需要示例数据集,这里可能需要用户自己准备,或者生成虚拟数据。为了简化,可能使用一个CSV文件加载到Weka中,转换成Arff格式。 综上,整个项目结构大致如此。需要注意模型训练和加载的一致性,前端与后端的数据传输格式(如Transaction DTO的字段匹配),以及Weka库的正确使用。最后,用户可能需要更多的细节,比如如何处理分类变量,如何部署,或者如何提高模型性能。因此,相关问题可能涉及这些方面。</think>使用IntelliJ IDEA社区版构建的简易机器学习欺诈检测系统实现方案,采用Spring Boot后端 + 简单HTML前端 + Weka机器学习库: 项目结构: ``` fraud-detection/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── fraud/ │ │ │ ├── controller/ │ │ │ │ └── FraudController.java │ │ │ ├── service/ │ │ │ │ └── FraudService.java │ │ │ ├── model/ │ │ │ │ ├── Transaction.java │ │ │ │ └── FraudResult.java │ │ │ └── Application.java │ │ └── resources/ │ │ ├── static/ │ │ │ └── index.html │ │ └── model/ │ │ └── fraud_model.model ├── pom.xml ``` 关键代码实现: 1. 后端控制器 (FraudController.java) ```java @RestController @RequestMapping("/api") @CrossOrigin public class FraudController { private final FraudService fraudService; @Autowired public FraudController(FraudService fraudService) { this.fraudService = fraudService; } @PostMapping("/detect") public ResponseEntity<FraudResult> detectFraud(@RequestBody Transaction transaction) { return ResponseEntity.ok(fraudService.detect(transaction)); } } ``` 2. 服务层 (FraudService.java) ```java @Service public class FraudService { private Classifier model; private Instances dataStructure; @PostConstruct public void init() throws Exception { // 加载预训练模型 model = (Classifier) SerializationHelper.read( getClass().getResourceAsStream("/model/fraud_model.model")); // 创建数据集结构(需与训练时一致) ArrayList<Attribute> attributes = new ArrayList<>(); attributes.add(new Attribute("amount")); attributes.add(new Attribute("category", Arrays.asList("0", "1", "2"))); attributes.add(new Attribute("time_of_day")); attributes.add(new Attribute("fraud", Arrays.asList("0", "1"))); dataStructure = new Instances("Transaction", attributes, 0); dataStructure.setClassIndex(3); } public FraudResult detect(Transaction transaction) { try { Instance instance = new DenseInstance(4); instance.setValue(0, transaction.getAmount()); instance.setValue(1, String.valueOf(transaction.getCategory())); instance.setValue(2, transaction.getTimeOfDay()); instance.setDataset(dataStructure); double prediction = model.classifyInstance(instance); return new FraudResult(prediction == 1.0); } catch (Exception e) { throw new RuntimeException("Prediction failed", e); } } } ``` 3. 前端页面 (index.html) ```html <!DOCTYPE html> <html> <head> <title>Fraud Detection</title> <style> .container { max-width: 600px; margin: 50px auto; padding: 20px; } .input-group { margin: 10px 0; } input { width: 100%; padding: 8px; } button { padding: 10px 20px; background: #007bff; color: white; border: none; } </style> </head> <body> <div class="container"> <h2>Transaction Check</h2> <div class="input-group"> <input type="number" id="amount" placeholder="Amount"> </div> <div class="input-group"> <input type="number" id="category" placeholder="Category (0-2)"> </div> <div class="input-group"> <input type="number" id="time" placeholder="Time (0-23)"> </div> <button onclick="checkFraud()">Check Transaction</button> <div id="result" style="margin-top: 20px;"></div> </div> <script> function checkFraud() { const payload = { amount: parseFloat(document.getElementById(&#39;amount&#39;).value), category: parseInt(document.getElementById(&#39;category&#39;).value), timeOfDay: parseInt(document.getElementById(&#39;time&#39;).value) }; fetch(&#39;http://localhost:8080/api/detect&#39;, { method: &#39;POST&#39;, headers: { &#39;Content-Type&#39;: &#39;application/json&#39; }, body: JSON.stringify(payload) }) .then(response => response.json()) .then(data => { const resultDiv = document.getElementById(&#39;result&#39;); resultDiv.innerHTML = data.fraud ? &#39;<h3 style="color: red">Fraud Detected!</h3>&#39; : &#39;<h3 style="color: green">Legitimate Transaction</h3>&#39;; }); } </script> </body> </html> ``` 4. 模型训练示例代码 (需要单独运行) ```java public class ModelTrainer { public static void main(String[] args) throws Exception { // 创建示例数据集 ArrayList<Attribute> attributes = new ArrayList<>(); attributes.add(new Attribute("amount")); attributes.add(new Attribute("category", Arrays.asList("0", "1", "2"))); attributes.add(new Attribute("time_of_day")); attributes.add(new Attribute("fraud", Arrays.asList("0", "1"))); Instances data = new Instances("FraudData", attributes, 1000); data.setClassIndex(3); // 添加示例数据(实际应使用真实数据集) Random random = new Random(123); for (int i = 0; i < 1000; i++) { Instance instance = new DenseInstance(4); instance.setValue(0, random.nextDouble() * 1000); instance.setValue(1, String.valueOf(random.nextInt(3))); instance.setValue(2, random.nextInt(24)); instance.setValue(3, random.nextDouble() > 0.95 ? "1" : "0"); data.add(instance); } // 训练模型 Classifier classifier = new RandomForest(); classifier.buildClassifier(data); // 保存模型 SerializationHelper.write("fraud_model.model", classifier); } } ``` 运行步骤: 1. 在pom.xml中添加Weka依赖: ```xml <dependency> <groupId>nz.ac.waikato.cms.weka</groupId> <artifactId>weka-stable</artifactId> <version>3.8.6</version> </dependency> ``` 2. 运行Application.java启动Spring Boot服务 3. 访问http://localhost:8080 这个实现包含: - 基于Weka的机器学习模型加载和预测 - RESTful API接口 - 简单的前端交互界面 - 示例模型训练代码 - 完整的Spring Boot应用结构
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值