SVM算法的python实现

1.随机生成几簇点

随机生成以(1,1,1)(5,5,5)(6,0,0)(10,10,10)(0,6,0)(10,10,2)为中心的6组散点坐标。

要求每个中心20个点,每个中心生成的随机点拥有同样的标签0~5,坐标为整数,存入exel文件。

import pandas as pd
import numpy as np

# 设置中心点和标签
centers = [(1, 1, 1), (5, 5, 5), (6, 0, 0), (10, 10, 10), (0, 6, 0), (10, 10, 2)]
labels = [0, 1, 2, 3, 4, 5]

# 设置每个中心生成的点数
points_per_center = 20

# 设置最大距离
max_distance = 3

# 生成散点坐标
points = []
for center, label in zip(centers, labels):
    for _ in range(points_per_center):
        distance = np.random.uniform(0, max_distance)
        phi = np.random.uniform(0, 2 * np.pi)
        theta = np.random.uniform(0, np.pi)

        x = center[0] + distance * np.sin(theta) * np.cos(phi)
        y = center[1] + distance * np.sin(theta) * np.sin(phi)
        z = center[2] + distance * np.cos(theta)

        points.append((int(x), int(y), int(z), label))

# 创建DataFrame
df = pd.DataFrame(points, columns=['X', 'Y', 'Z', 'Label'])

# 保存到Excel文件
df.to_excel('random_points.xlsx', index=False)

效果图

SVM算法的python实现_第1张图片

 2.将生成的点簇可视化

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 读取Excel文件
df = pd.read_excel('random_points.xlsx')

# 3D散点图
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# 遍历每个标签,绘制对应的散点图
for label in df['Label'].unique():
    label_data = df[df['Label'] == label]
    ax.scatter(label_data['X'], label_data['Y'], label_data['Z'], label=f'Label {label}')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Random Points Visualization')

plt.show()

 效果图

SVM算法的python实现_第2张图片

3.使用SVM分类及可视化

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

# 读取Excel文件
df = pd.read_excel('random_points.xlsx')

# 准备数据
X = df[['X', 'Y', 'Z']].to_numpy()  # 将DataFrame转换为numpy数组
y = df['Label']

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

# 合并训练集和测试集数据
X_combined = np.vstack([X_train, X_test])
y_combined = pd.concat([y_train, y_test])

# 训练SVM模型
svm_model = SVC(kernel='linear', decision_function_shape='ovo')  # 使用一对一策略
svm_model.fit(X_train, y_train)

# 预测测试集
y_pred = svm_model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Test Accuracy: {accuracy:.2f}')

# 可视化分类结果
fig = plt.figure(figsize=(12, 10))
ax = fig.add_subplot(111, projection='3d')

# 绘制所有数据点
for label in y_combined.unique():
    label_data = X_combined[y_combined == label]
    ax.scatter(label_data[:, 0], label_data[:, 1], label_data[:, 2], label=f'Combined Label {label}')
# Combined Label表示 训练和测试放一张图

# 绘制分类平面
xx, yy = np.meshgrid(np.linspace(X[:, 0].min(), X[:, 0].max(), 50),
                     np.linspace(X[:, 1].min(), X[:, 1].max(), 50))
zz = np.zeros_like(xx)

for i in range(len(xx)):
    for j in range(len(yy)):
        decision_function_values = svm_model.decision_function([[xx[i, j], yy[i, j], zz[i, j]]])
        zz[i, j] = decision_function_values.argmax()

ax.plot_surface(xx, yy, zz, alpha=0.3, color='gray')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('SVM Classification (One-vs-One)')

plt.legend()
plt.show()

# 连续输入坐标并进行预测
while True:
    user_input_x = input('Enter X coordinate (or "q" to quit): ')

    if user_input_x.lower() == 'q':
        break

    try:
        user_input_x = float(user_input_x)
        user_input_y = float(input('Enter Y coordinate: '))
        user_input_z = float(input('Enter Z coordinate:'))

        # 预测用户输入坐标的类别
        user_input_data = np.array([[user_input_x, user_input_y, user_input_z]])
        user_prediction = svm_model.predict(user_input_data)

        print(f'The predicted label for the user input coordinates is: {user_prediction[0]}')

    except ValueError:
        print('Invalid input. Please enter numerical values for coordinates.')

可视化效果

SVM算法的python实现_第3张图片

键盘输入进行测试

SVM算法的python实现_第4张图片

 参考

chatgpt3.5

https://chat.openai.com/

你可能感兴趣的:(算法,支持向量机,python)