【问题标题】:print prediction results in CSV file在 CSV 文件中打印预测结果
【发布时间】:2021-05-07 16:18:52
【问题描述】:

我应用了许多深度学习技术,每个模型都有一个结果,我想在 CSV 文件中打印预测(类标签)。 这是我使用的代码

# load model
model = keras.models.load_model('bestmodelslstm.h5')

df = train[['clean_tweet_no_stop','Affect Dimension']]
df.head()
#output
clean_tweet_no_stop                                     Affect Dimension
0   النهارده كنت قاعد البيت مرعوب صوت جمهور الدر... fear
1   اول مره اشوف حديقه وسط طرق سريعه مواقف سيارا... fear
2   اي حلو وانت مرعب العالم حاط السكين يمينك ال...  fear
3   الأنظمة تمارس الحجب الكلمة والرأي المخالف أ...  fear
4   وحيد جدا أغلق هاتفي بلا خوف يقلق بشأني أحد أ... fear

train.shape
#(5600, 2)

labels = np.array(df['Affect Dimension'])
y = []
for i in range(len(df["Affect Dimension"])):
    if labels[i] == 'anger':
        y.append(0)
    if labels[i] == 'fear':
        y.append(1)
    if labels[i] == 'joy':
        y.append(2)
    if labels[i] == 'sadness':
        y.append(3)
y = np.array(y)
labels = tf.keras.utils.to_categorical(y, 4, dtype="float32")
del y

print(labels)
#output
[[0. 1. 0. 0.]
 [0. 1. 0. 0.]
 [0. 1. 0. 0.]
 ...
 [0. 0. 0. 1.]
 [0. 0. 0. 1.]
 [0. 0. 0. 1.]]

X_train, X_test, y_train, y_test = train_test_split(tweets,labels, test_size=0.25, random_state=0)
print (len(X_train),len(X_test),len(y_train),len(y_test))
#4200 1400 4200 1400


test_loss, test_acc = model1.evaluate(X_test, y_test, verbose=2)
print('Model accuracy: ',test_acc)
predictions = model1.predict(X_test)
matrix = confusion_matrix(y_test.argmax(axis=1), np.around(predictions, decimals=0).argmax(axis=1))

#Model accuracy:  0.4235714285714286

pd.DataFrame(matrix, index = ['Anger','Fear','Joy', 'Sadness'],columns = ['Anger','Fear','Joy', 'Sadness'])


from sklearn.metrics import classification_report
print(classification_report(np.argmax(y_test, axis=1), np.argmax(predictions, axis=1)))

print(predictions)

#Output for prediction for each emotion and predict labels 
[[3.1125692e-01 3.5565314e-01 9.2857322e-03 3.2380414e-01]
 [3.4271225e-01 4.1075385e-01 4.9968611e-04 2.4603422e-01]
 [3.3079410e-01 3.0755761e-01 4.6885073e-02 3.1476316e-01]
 ...
 [2.8897709e-01 4.5005488e-01 4.4657052e-05 2.6092330e-01]
 [3.3190650e-01 3.2205048e-01 2.6132595e-02 3.1991041e-01]
 [8.9242887e-03 6.6916817e-03 9.7304100e-01 1.1342982e-02]]

predictions.shape
(1400, 4)

import numpy as np
import pandas as pd

my_results=pd.DataFrame(matrix, index = ['Anger','Fear','Joy', 'Sadness'],columns = ['Anger','Fear','Joy', 'Sadness'])

my_results
#   Anger   Fear    Joy Sadness
Anger   328 1   24  0
Fear    350 3   8   0
Joy 134 0   188 0
Sadness 337 1   26  0

from sklearn.metrics import classification_report
print(classification_report(np.argmax(y_test, axis=1), np.argmax(predictions, axis=1)))

    precision    recall  f1-score   support

           0       0.40      0.16      0.23       353
           1       0.36      0.57      0.44       361
           2       0.63      0.75      0.69       322
           3       0.29      0.25      0.27       364

    accuracy                           0.42      1400
   macro avg       0.42      0.43      0.41      1400
weighted avg       0.41      0.42      0.40      1400

#prediction = pd.DataFrame(predictions, columns=['anger', 'Fear', 'Joy', 'Sadness']).to_csv('prediction.csv')```

但我得到了一个 CSV 文件,其中包含每种情绪的值,没有预测类标签或真实标签(原始)!

我想打印推文和原始类标签并预测类标签?

【问题讨论】:

    标签: python csv prediction


    【解决方案1】:

    为输入创建一个数据框

    my_results=pd.DataFrame(matrix, index = ['Anger','Fear','Joy', 'Sadness'],columns = ['Anger','Fear','Joy', 'Sadness'])
    

    然后将预测添加到它。

    my_results['prediction']=predictions
    
    

    然后保存 csv。

    my_results.to_csv("Result.csv",index=False)
    

    【讨论】:

    • Thnx,但在运行添加预测时出现此错误:ValueError: Length of values does not match length of index,
    • 能否根据新代码打印my_results.shape?注释掉添加预测行并根据您的原始代码打印prediction.shape
    • predictions.shape ((1400, 4)), my_results.shape : 打印每个情绪的分布式混淆矩阵
    • 那么我认为,您首先需要 CSV 格式的 X_test 数据。打印 X_test 的形状。有一些缺失的部分。例如,您的输出层的形状为 4,您真的要在输出中放入 4 个值还是这 4 个值的最大值索引?你能把完整的代码和数据集一起发布吗?
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2020-10-05
    • 2022-12-11
    • 2016-04-24
    • 1970-01-01
    • 2014-09-03
    • 2020-04-17
    • 2019-07-15
    相关资源
    最近更新 更多