简单代码应用
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语言代码实现了一个简单的决策树分类器。