对于9大类,14000条数据,怎么解决分类的问题。
人工分类,一定可以。
还是先人工分上几类,然后再利用机器学习生成模型(pk1格式)
话不多说直接上代码。
import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report, accuracy_score from sklearn.pipeline import Pipeline import joblib # 加载数据集 data = pd.read_excel('D:/builds/最新物资信息卡片(0226版)自动学习及分类.xlsx') # 数据预处理 data['物资名称'] = data['物资名称'].str.lower() # 转换为小写 data['物资名称'] = data['物资名称'].str.replace(r'\W+', ' ') # 替换非字母数字字符为空格 # 分割数据集 X = data['物资名称'] y = data['类别'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 创建MultinomialNB实例并设置参数 nb_classifier = MultinomialNB(alpha=1e-3) # 初始alpha值 # 创建管道 pipeline = Pipeline([ ('tfidfvectorizer', TfidfVectorizer()), ('multinomialnb', nb_classifier) # 使用已设置参数的MultinomialNB ]) # 设置参数网格 parameters = { 'tfidfvectorizer__max_features': [5000, 10000, 15000], 'tfidfvectorizer__ngram_range': [(1, 1), (1, 2), (2, 3)], 'tfidfvectorizer__stop_words': ['english'], 'multinomialnb__alpha': [1e-3, 1e-4, 1e-5] # 注意这里的参数名称 } # 创建GridSearchCV对象 grid_search = GridSearchCV(pipeline, parameters, cv=5, scoring='accuracy') # 使用训练数据进行参数调优 grid_search.fit(X_train, y_train) # 打印最佳参数 print("Best parameters found: ", grid_search.best_params_) # 使用最佳参数重新训练模型 best_model = grid_search.best_estimator_ # 保存最佳模型 joblib.dump(best_model, 'D:/builds/优化后的物资分类模型.pkl') # 读取新文件进行预测 new_data = pd.read_excel('D:/builds/1测试模型冲.xlsx') new_data['物资名称'] = new_data['物资名称'].str.lower() new_data['物资名称'] = new_data['物资名称'].str.replace(r'\W+', ' ') # 使用新模型进行预测 # 使用新模型进行预测 predictions = best_model.predict(new_data['物资名称']) # 在新数据集 DataFrame 中创建 '预测分类' 列 new_data['预测分类'] = predictions # 对比预测结果与实际分类,并打印结果 print(new_data[['物资名称', '分类', '预测分类']]) # 计算准确率并赋值给变量 accuracy = accuracy_score(new_data['分类'], predictions) print("Accuracy:", accuracy) # 将结果写入新的Excel文件 output_data = new_data[['物资名称', '分类', '预测分类']] output_data.to_excel('D:/builds/预测结果.xlsx', index=False) # 如果你还想记录准确率,可以创建一个新的DataFrame accuracy_report = pd.DataFrame({'Accuracy': [accuracy]}) accuracy_report.to_excel('D:/builds/准确率报告.xlsx', index=False)
下图为最新物资信息卡片(0226版)自动学习及分类.xlsx截图
然后是不是测试一下模型kp1如何,安排。
对于空白的分类,如何补齐?下图为空测试模型冲.xlsx
完整代码如下:
import pandas as pd import joblib # 加载训练好的模型 model = joblib.load('D:/builds/优化后的物资分类模型.pkl') # 读取新的Excel文件 new_data = pd.read_excel('D:/builds/空测试模型冲.xlsx') # 数据预处理(确保与模型训练时的预处理一致) # 这里假设新的Excel文件中的列名是 '物资名称' 和 '分类' new_data['物资名称'] = new_data['物资名称'].str.lower() new_data['物资名称'] = new_data['物资名称'].str.replace(r'\W+', ' ') # 使用模型进行预测 predictions = model.predict(new_data['物资名称']) # 将预测结果更新到 '分类' 列 new_data['分类'] = predictions # 将更新后的数据保存回Excel文件 new_data.to_excel('D:/builds/空测试模型冲_预测结果.xlsx', index=False)