python 机器学习代码仅在使用训练数据进行测试时才起作用,否则会给出错误的答案

5kgi1eie  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(98)

首先,谢谢你回答我的问题。我正在尝试开发一个机器学习模型,它可以对3种不同的表面粗糙度进行分类(类型1,2,3)当用图像数据进行测试时。训练数据是使用5组2-D图像构建的这意味着总共15个图像和15个点云被用于开发训练数据集。下面的代码可以工作,但当我尝试测试一个新的图像时给出了错误的答案,但当我使用训练数据中的图像测试代码时,它可以正常工作。有人可以帮助吗?

import numpy as np
    import os
    import cv2
    from sklearn.model_selection import train_test_split
    from sklearn.svm import SVC
    
    data = []
    labels = []

# Loop through the three types of surface roughness types

    for i in range(1, 4):
        type_path = f"D:\\Ph.D. IEE\\Research\\My research\\Images\\type{i}"
    # Loop through the 5 images and point clouds for each type
for j in range(1, 6):
    # Read in the image and point cloud files
    image_path = os.path.join(type_path, f"{j}.png")
    point_cloud_path = os.path.join(type_path, f"{j}.csv")
    image = cv2.imread(image_path)
    point_cloud = np.loadtxt(point_cloud_path, delimiter='\t')
        # Append the image and point cloud to the data list
        data.append((image, point_cloud))
        # Append the label to the labels list
        labels.append(i)

# Convert the data and labels lists to NumPy arrays
data = np.array(data)
labels = np.array(labels)

# Split the dataset into training and testing sets
train_data, test_data, train_labels, test_labels = train_test_split(data, labels, test_size=0.2, random_state=42)

# Reshape the training and testing data
train_images = train_data[:, 0]
train_images = np.array([cv2.resize(img, (1024, 768)) for img in train_images])
train_point_clouds = train_data[:, 1]
train_labels = np.array(train_labels)

test_images = test_data[:, 0]
test_images = np.array([cv2.resize(img, (1024, 768)) for img in test_images])
test_point_clouds = test_data[:, 1]
test_labels = np.array(test_labels)

# Train a machine learning model on the training data
svm_model = SVC(kernel='linear')
svm_model.fit(train_images.reshape(-1, 1024*768*3), train_labels)

# Make a prediction on a testing image
test_image_path = "D:\\Ph.D. IEE\\Research\\My research\\Test\\t6.png"
test_image = cv2.imread(test_image_path)
test_image = cv2.resize(test_image, (1024, 768))
prediction = svm_model.predict(test_image.reshape(1, -1))[0]

# Map the prediction to the corresponding surface roughness type
if prediction == 1:
    print("The testing image falls under surface roughness type 1.")
elif prediction == 2:
    print("The testing image falls under surface roughness type 2.")
elif prediction == 3:
    print("The testing image falls under surface roughness type 3.")
else:
    print("The trained model could not predict the surface roughness. ")
0yycz8jy

0yycz8jy1#

你可能是overfitting。当你过拟合时,你可以尝试的一件事是简化模型(即:如果这不起作用,您可能需要更多的数据,或者您可能需要augment your data

相关问题