2024美赛C题(网球的动力)深度剖析|详细建模+代码实现(决策树+时间序列+支持向量机)

6 篇文章 0 订阅
6 篇文章 0 订阅

首先回顾一下本次美赛的C题:

问题1的解决思路如下:

python示例代码:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

# 读取数据集
data = pd.read_csv('Wimbledon_featured_matches.csv')

# 选择一个比赛(match_id为示例值)
match_id = '2023-wimbledon-1701'
selected_match = data[data['match_id'] == match_id]

# 提取关键时间序列特征
time_series_features = ['set_no', 'game_no', 'point_no', 'server', 'receiver', 'winner']

# 创建时间序列数据
time_series_data = selected_match[time_series_features]

# 按照时间顺序排序
time_series_data = time_series_data.sort_values(by=['set_no', 'game_no', 'point_no'])

# 特征工程
X = time_series_data[['set_no', 'game_no', 'point_no']]
y = time_series_data['winner']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 随机森林模型建立
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 模型预测
y_pred = model.predict(X_test)

# 模型评估
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)

print(f'Accuracy: {accuracy}')
print(f'Confusion Matrix:\n{conf_matrix}')

# 时间序列可视化
plt.figure(figsize=(12, 6))

# 绘制比赛过程的折线图
plt.plot(time_series_data['point_no'], time_series_data['server'], label='Server')
plt.plot(time_series_data['point_no'], time_series_data['receiver'], label='Receiver')
plt.scatter(X_test['point_no'], y_pred, color='red', marker='x', label='Predicted Winner')

plt.title('Match Performance Time Series')
plt.xlabel('Point Number')
plt.ylabel('Player')
plt.legend()
plt.show()

matlab示例代码:

% 读取数据集
data = readtable('Wimbledon_featured_matches.csv');

% 选择一个比赛(match_id为示例值)
match_id = '2023-wimbledon-1701';
selected_match = data(data.match_id == match_id, :);

% 提取关键时间序列特征
time_series_features = {'set_no', 'game_no', 'point_no', 'server', 'receiver', 'winner'};
time_series_data = selected_match(:, time_series_features);

% 按照时间顺序排序
time_series_data = sortrows(time_series_data, {'set_no', 'game_no', 'point_no'});

% 特征工程
X = time_series_data{:, {'set_no', 'game_no', 'point_no'}};
y = time_series_data.winner;

% 划分训练集和测试集
rng(42);  % 设置随机种子以保证可复现性
[trainIdx, testIdx] = cvpartition(height(time_series_data), 'HoldOut', 0.2);
X_train = X(trainIdx, :);
y_train = y(trainIdx);
X_test = X(testIdx, :);
y_test = y(testIdx);

% 随机森林模型建立
model = TreeBagger(100, X_train, y_train, 'Method', 'classification', 'OOBPrediction', 'on');

% 模型预测
y_pred = predict(model, X_test);

% 模型评估
accuracy = sum(strcmp(y_pred, y_test)) / numel(y_test);
conf_matrix = confusionmat(y_test, y_pred);

fprintf('Accuracy: %.4f\n', accuracy);
disp('Confusion Matrix:');
disp(conf_matrix);

% 时间序列可视化
figure;
plot(time_series_data.point_no, time_series_data.server, 'DisplayName', 'Server');
hold on;
plot(time_series_data.point_no, time_series_data.receiver, 'DisplayName', 'Receiver');
scatter(X_test(:, 3), str2double(y_pred), 50, 'rx', 'DisplayName', 'Predicted Winner');
hold off;

title('Match Performance Time Series');
xlabel('Point Number');
ylabel('Player');
legend('Server', 'Receiver', 'Predicted Winner');

问题3可以采用支持向量机的思路建模:

python示例代码:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

features = match_data[['feature1', 'feature2', ...]]
target = match_data['fluctuation']

# 数据标签处理,将波动作为目标变量,转换为二进制分类问题
target_binary = (target == '波动')  # 根据实际数据标签调整

# 数据拆分为训练集和测试集
train_features, test_features, train_target, test_target = train_test_split(features, target_binary, test_size=0.2, random_state=42)

# 特征缩放,使用 z-score 标准化
scaler = StandardScaler()
train_features_scaled = scaler.fit_transform(train_features)
test_features_scaled = scaler.transform(test_features)

# SVM 模型训练
svm_model = SVC(kernel='linear', C=1)
svm_model.fit(train_features_scaled, train_target)

# 模型预测
predictions = svm_model.predict(test_features_scaled)

# 模型评估
accuracy = accuracy_score(test_target, predictions)
print(f'SVM Model Accuracy: {accuracy:.4f}')

matlab示例代码:

features = match_data(:, {'feature1', 'feature2', ...});
target = match_data.fluctuation;

% 数据标签处理,将波动作为目标变量,转换为二进制分类问题
target_binary = (target == '波动');  % 根据实际数据标签调整

% 数据拆分为训练集和测试集
rng(42);  % 设置随机种子,确保结果可重复
[train_features, test_features, train_target, test_target] = splitData(features, target_binary, 0.8);

% 特征缩放,使用 z-score 标准化
train_features_scaled = zscore(train_features);
test_features_scaled = zscore(test_features);

% SVM 模型训练
svm_model = fitcsvm(train_features_scaled, train_target, 'KernelFunction', 'linear', 'BoxConstraint', 1);

% 模型预测
predictions = predict(svm_model, test_features_scaled);

% 模型评估
accuracy = sum(predictions == test_target) / length(test_target);
fprintf('SVM Model Accuracy: %.4f\n', accuracy);

查看完整思路如下:

【腾讯文档】2024美赛全题目深度解析(建模过程+代码实现+论文指导)
https://docs.qq.com/doc/DSG1LQWtOQ3lFWHNj

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问!以下是基于Arduino和OpenCV实现代码,用于实现基于视觉算法的自主网球拾捡机器人,并且具有人脸追踪功能。希望对您有所帮助! 首先,我们需要准备以下硬件和软件: 硬件: 1. Arduino板子 2. 电机驱动模块 3. 摄像头模块 4. 机械臂 5. 电池组 6. 网球 软件: 1. Arduino IDE 2. OpenCV库 3. Python 2.7 接下来,我们来看一下实现代码: Arduino代码: ```C++ #include <Servo.h> #include <AFMotor.h> AF_DCMotor motor1(1, MOTOR12_64KHZ); AF_DCMotor motor2(2, MOTOR12_64KHZ); AF_DCMotor motor3(3, MOTOR34_64KHZ); AF_DCMotor motor4(4, MOTOR34_64KHZ); Servo myservo1; Servo myservo2; Servo myservo3; Servo myservo4; void setup() { Serial.begin(9600); myservo1.attach(9); myservo2.attach(10); myservo3.attach(11); myservo4.attach(12); } void loop() { int ball_x = 0; //球的x坐标 int ball_y = 0; //球的y坐标 int face_x = 0; //人脸的x坐标 int face_y = 0; //人脸的y坐标 //从Python中读取球和人脸的坐标 if(Serial.available() > 0) { ball_x = Serial.parseInt(); ball_y = Serial.parseInt(); face_x = Serial.parseInt(); face_y = Serial.parseInt(); } //控制机械臂抓取球 if(ball_x != 0 && ball_y != 0) { if(ball_x < 200) { motor1.run(BACKWARD); motor2.run(BACKWARD); } else if(ball_x > 400) { motor1.run(FORWARD); motor2.run(FORWARD); } else { motor1.run(RELEASE); motor2.run(RELEASE); } if(ball_y < 200) { motor3.run(BACKWARD); motor4.run(BACKWARD); } else if(ball_y > 400) { motor3.run(FORWARD); motor4.run(FORWARD); } else { motor3.run(RELEASE); motor4.run(RELEASE); } } else { motor1.run(RELEASE); motor2.run(RELEASE); motor3.run(RELEASE); motor4.run(RELEASE); } //控制机械臂放下球 if(face_x != 0 && face_y != 0) { myservo1.write(90); myservo2.write(90); myservo3.write(90); myservo4.write(90); } else { myservo1.write(0); myservo2.write(0); myservo3.write(0); myservo4.write(0); } } ``` Python代码: ```Python import cv2 import serial ser = serial.Serial('COM3', 9600) #连接Arduino face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #人脸检测器 cap = cv2.VideoCapture(0) #打开摄像头 while True: ret, img = cap.read() #读取摄像头的图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #将图像转换为灰度图像 faces = face_cascade.detectMultiScale(gray, 1.3, 5) #检测人脸 for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #在人脸周围画矩形框 ser.write(str(x + w/2) + ' ' + str(y + h/2) + ' 0 0\n') #将人脸中心坐标发送给Arduino hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #将图像转换为HSV颜色空间 lower_red = np.array([0, 50, 50]) #设置红色的HSV阈值 upper_red = np.array([10, 255, 255]) mask1 = cv2.inRange(hsv, lower_red, upper_red) lower_red = np.array([170, 50, 50]) upper_red = np.array([180, 255, 255]) mask2 = cv2.inRange(hsv, lower_red, upper_red) mask = mask1 + mask2 #将两个红色区域的mask相加 contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #寻找所有的轮廓 max_area = 0 ball_x = 0 ball_y = 0 for i in range(len(contours)): area = cv2.contourArea(contours[i]) #计算轮廓面积 if area > max_area: max_area = area max_contour = contours[i] (ball_x, ball_y), radius = cv2.minEnclosingCircle(max_contour) #计算最小外接圆的圆心坐标和半径 if max_area > 100: cv2.circle(img, (int(ball_x), int(ball_y)), int(radius), (0, 255, 0), 2) #在球周围画圆 ser.write('0 0 ' + str(int(ball_x)) + ' ' + str(int(ball_y)) + '\n') #将球的中心坐标发送给Arduino cv2.imshow('img', img) #显示图像 if cv2.waitKey(1) & 0xFF == ord('q'): #按下q键退出 break cap.release() cv2.destroyAllWindows() ``` 以上代码实现了一个基于Arduino和OpenCV的自主网球拾捡机器人,并且具有人脸追踪功能。在代码中,我们使用了Arduino控制机械臂抓取和放下球,使用了OpenCV检测人脸和球,并且使用了Python将人脸和球的坐标发送给Arduino。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值