当前位置: 首页 > news >正文

简单代码应用

Python使用 TensorFlow 库构建一个简单的手写数字识别的卷积神经网络(CNN)模型,C语言实现一个简单的基于决策树的分类器(模拟人工智能中分类的应用),这两个示例相对复杂一些,能更好地体现人工智能相关的概念和应用:
 
Python使用TensorFlow构建手写数字识别的CNN模型代码
 
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.utils import to_categorical

# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 数据预处理
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# 构建卷积神经网络模型
model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    MaxPooling2D((2, 2)),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D((2, 2)),
    Flatten(),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax')
])

# 编译模型
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

# 在测试集上评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"测试集准确率: {test_acc}")
 
 
C语言实现简单的基于决策树的分类器代码(这里只是简单模拟,实际应用会复杂很多)
 
#include <stdio.h>
#include <stdlib.h>

// 简单的数据结构表示样本,这里假设只有两个特征和一个类别标签
typedef struct {
    float feature1;
    float feature2;
    int label;
} Sample;

// 简单的决策树节点结构
typedef struct TreeNode {
    int is_leaf;
    int label;
    float split_value;
    int split_feature;
    struct TreeNode *left;
    struct TreeNode *right;
} TreeNode;

// 创建一个新的决策树节点
TreeNode* createTreeNode() {
    TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
    node->is_leaf = 0;
    node->label = -1;
    node->split_value = 0.0;
    node->split_feature = 0;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// 简单的决策树构建函数(这里只是非常简单的模拟,实际很复杂)
TreeNode* buildDecisionTree(Sample samples[], int num_samples) {
    TreeNode* root = createTreeNode();
    // 这里简单假设根据第一个特征进行划分
    root->split_feature = 0;
    root->split_value = 0.5;  // 简单设定一个划分值

    // 划分样本到左右子树
    int left_count = 0;
    int right_count = 0;
    Sample left_samples[num_samples];
    Sample right_samples[num_samples];
    for (int i = 0; i < num_samples; i++) {
        if (samples[i].feature1 < root->split_value) {
            left_samples[left_count++] = samples[i];
        } else {
            right_samples[right_count++] = samples[i];
        }
    }

    // 如果左子树有样本,继续构建左子树
    if (left_count > 0) {
        root->left = buildDecisionTree(left_samples, left_count);
    }
    // 如果右子树有样本,继续构建右子树
    if (right_count > 0) {
        root->right = buildDecisionTree(right_samples, right_count);
    }

    // 假设是叶子节点时,根据多数类确定标签
    if (left_count == 0 && right_count == 0) {
        root->is_leaf = 1;
        int label_count[2] = {0, 0};
        for (int i = 0; i < num_samples; i++) {
            label_count[samples[i].label]++;
        }
        root->label = (label_count[0] > label_count[1])? 0 : 1;
    }

    return root;
}

// 预测函数
int predict(TreeNode* root, Sample sample) {
    if (root->is_leaf) {
        return root->label;
    }
    if (sample.feature1 < root->split_value) {
        return predict(root->left, sample);
    } else {
        return predict(root->right, sample);
    }
}

int main() {
    // 简单的样本数据
    Sample samples[] = {
        {0.2, 0.3, 0},
        {0.4, 0.6, 1},
        {0.1, 0.2, 0},
        {0.7, 0.8, 1}
    };
    int num_samples = sizeof(samples) / sizeof(samples[0]);

    TreeNode* root = buildDecisionTree(samples, num_samples);

    // 测试预测
    Sample test_sample = {0.3, 0.4};
    int prediction = predict(root, test_sample);
    printf("预测结果: %d\n", prediction);

    return 0;
}
 
 
上述Python代码构建并训练了一个用于手写数字识别的CNN模型,C语言代码实现了一个简单的决策树分类器。

相关文章:

  • Linux(autoDL云服务器)mamba-ssm环境安装——一次成功!
  • 【计算机网络 | 第二篇】常见的通信协议(一)
  • 【HDFS入门】HDFS数据冗余与容错机制解析:如何保障大数据高可靠存储?
  • day29 学习笔记
  • 洛谷题目:P8624 [蓝桥杯 2015 省 AB] 垒骰子 题解 (本题简)
  • linux kernel irq相关函数详解
  • 系分架构论文《论高并发场景的架构设计和开发方法》
  • 股指期货跨期套利是如何赚取价差利润的?
  • Java实现将MarkDown保留文档内容及格式输出到浏览器页面
  • 基于控制台的小车导航游戏开发详解(C++实现)
  • 嘉立创原理图、PCB常见问题
  • 10.thinkphp的响应
  • MCP协议驱动的功能纳米材料设计及其在光催化甲烷偶联中的创新应用
  • CPU Loading and Task Loading Visualization Tool
  • 加一:从简单问题到复杂边界的深度思考
  • 每日一记:CRT和图论
  • 【软考-高级】【信息系统项目管理师】【论文基础】资源管理过程输入输出及工具技术的使用方法
  • vue3专题1------父组件中更改子组件的属性
  • 【信息系统项目管理师】高分论文:论信息系统项目的干系人管理(商业银行绩效考核系统)
  • Prompt-Tuning 提示词微调
  • 东航推出“上博号”班机,上博设立“东航特展厅”
  • 轻流科技薄智元:AI时代,打造“工业智造”需要“共生式进化”
  • 2025年世界互联网大会亚太峰会人工智能大模型论坛举行
  • 日本多地发生无差别杀人事件,中使馆提醒中国公民加强安全防范
  • 居然智家:实控人、董事长兼CEO汪林朋被留置、立案,公司经营正常
  • 何立峰会见美国英伟达公司总裁黄仁勋:欢迎美资企业深耕中国市场