我的独立功能中的字母数字输入 - 错误:ValueError:无法将字符串转换为浮点数:'01232COM002-222'

问题描述 投票:0回答:1

我有 2 列,一列是独立的,表示 PART_NO,另一列是相关的,表示数量。 我试图根据特定机器是什么机器来预测其数量。现在的问题是我的 PART_NO 有字母数字字符,例如 01232COM002-222、ABCD/235、GS.612.90-19、123456。

当我使用 RandomForestRegressor 拟合模型时,我得到

error: could not convert string to float, 

我无法用任何内容替换任何斜杠或逗号,因为 PART_NO 是唯一的。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import LinearSVR
from sklearn.linear_model import LinearRegression
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import classification_report
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import LabelEncoder

file = 'testData.xlsx'
df = pd.read_excel(file)
df.head()

print(f"Number of rows = {df.shape[0]}")
print(f"Number of columns = {df.shape[1]}")

print("Data types of columns: \n", df.dtypes)

print("X-Features and y-Labels")
X = df[['PART_NO']]
y = df['QUANTITY']
print("X-Features\n")
print(X.head())
print("")
print("y-Labels")
print(y.head())


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)
print("Training size = ", X_train.shape)
print("Testing size = ", X_test.shape)
model = RandomForestRegressor()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("")
print(classification_report(y_test, y_pred))

我尝试过LabelEncoding、OneHotEncoding,没有用,我尝试过字符串替换,没有用。

python python-3.x machine-learning regression jupyter
1个回答
0
投票

在我看来,您需要将字母数字字符映射到唯一浮点数,最简单的方法似乎是使用 utf-8 编码的 ascii 将字母数字值转换为二进制,然后转换为基数 10 数字。 如果有重复项,只需保留基数 2、0 和 1 就可以生成浮点数,并且您确信它是唯一的 https://www.geeksforgeeks.org/python-convert-string-to-binary/了解将字符串转换为二进制的方法

另一种方法是简单地生成一个包含字母数字条目的字典 作为键和任意分布的数字作为值,就像这样:

numbers = {}
for i in range(len(x)):
    numbers[x[i]] = i

或更短的方式:

numbers = {x[i]:i for i in range(len(x))}
© www.soinside.com 2019 - 2024. All rights reserved.