dreamnotfound commited on
Commit
39770c3
·
1 Parent(s): eb4b777

Upload 4 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ gru/save/gru_model.keras filter=lfs diff=lfs merge=lfs -text
37
+ input/emotions.csv filter=lfs diff=lfs merge=lfs -text
gru/index_gru.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import seaborn as sns
4
+ import tensorflow as tf
5
+ import matplotlib.pyplot as plt
6
+ data = pd.read_csv('../input/emotions.csv')
7
+ data['label'].value_counts()
8
+ data.isnull().sum()
9
+ label_mapping = {'NEGATIVE': 0, 'NEUTRAL': 1, 'POSITIVE': 2}
10
+ data['label'] = data['label'].replace(label_mapping)
11
+ X = data.drop('label', axis=1).copy()
12
+ y = data['label'].copy()
13
+ from sklearn.model_selection import train_test_split
14
+ X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=42)
15
+ inputs = tf.keras.Input(shape=(X_train.shape[1],))
16
+ expand_dims = tf.expand_dims(inputs, axis=2)
17
+ gru = tf.keras.layers.GRU(256, return_sequences=True)(expand_dims)
18
+ flatten = tf.keras.layers.Flatten()(gru)
19
+ outputs = tf.keras.layers.Dense(3, activation='softmax')(flatten)
20
+ model = tf.keras.Model(inputs=inputs, outputs=outputs)
21
+
22
+ new_learning_rate = 1 # 设置学习率
23
+ model.compile(
24
+ optimizer=tf.keras.optimizers.Adam(learning_rate=new_learning_rate),
25
+ loss='sparse_categorical_crossentropy',
26
+ metrics=['accuracy']
27
+ )
28
+
29
+ model.compile(
30
+ optimizer='adam',
31
+ loss='sparse_categorical_crossentropy',
32
+ metrics=['accuracy']
33
+ )
34
+ print(model.summary())
35
+ history = model.fit( # 开始训练
36
+ X_train,
37
+ y_train,
38
+ validation_split=0.2,
39
+ batch_size=32,
40
+ epochs=50, # 训练50轮
41
+ callbacks=[
42
+ tf.keras.callbacks.EarlyStopping(
43
+ monitor='val_loss',
44
+ patience=5,
45
+ restore_best_weights=True
46
+ )
47
+ ]
48
+ )
49
+ model_acc = model.evaluate(X_test, y_test, verbose=0)[1]
50
+
51
+ print("Test Accuracy: {:.2f}%".format(model_acc * 100))
52
+ from sklearn.metrics import confusion_matrix
53
+ y_pred = np.array(list(map(lambda x: np.argmax(x), model.predict(X_test))))
54
+ cm = confusion_matrix(y_test, y_pred)
55
+
56
+ print("Confusion Matrix:\n",(cm))
57
+
58
+ plt.figure(figsize=(8, 8))
59
+ sns.heatmap(cm, annot=True, vmin=0, fmt='g', cbar=False, cmap='Blues')
60
+ plt.xticks(np.arange(3) + 0.5, label_mapping.keys())
61
+ plt.yticks(np.arange(3) + 0.5, label_mapping.keys())
62
+ plt.xlabel("Predicted")
63
+ plt.ylabel("Actual")
64
+ plt.title("Confusion Matrix")
65
+ plt.show()
66
+ from sklearn.metrics import classification_report
67
+ # Generate classification report
68
+ clr = classification_report(y_test, y_pred, target_names=label_mapping.keys())
69
+ print("Classification Report:\n----------------------\n", clr)
70
+ # Save the trained model to a file
71
+ model.save('save/gru_model.keras')
gru/run.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import tensorflow as tf
4
+
5
+ # Load the trained GRU model
6
+ loaded_model = tf.keras.models.load_model('save/gru_model.keras')
7
+
8
+ # Load new data for prediction
9
+ new_data = pd.read_csv('input/data.csv') # Replace with the path to your new data CSV file
10
+
11
+ # Preprocess the new data (similar to how you preprocessed the training data)
12
+ # Assuming the new_data has the same features as the training data
13
+ X_new = new_data.drop('label', axis=1)
14
+
15
+ # Make predictions on new data
16
+ predicted_labels = loaded_model.predict_classes(X_new)
17
+
18
+ # Map predicted labels back to emotions using the label_mapping dictionary
19
+ reverse_label_mapping = {v: k for k, v in label_mapping.items()}
20
+ predicted_emotions = [reverse_label_mapping[label] for label in predicted_labels]
21
+
22
+ # Add predicted emotions to the new_data DataFrame
23
+ new_data['predicted_emotion'] = predicted_emotions
24
+
25
+ # Print the new_data DataFrame with predicted emotions
26
+ print(new_data)
gru/save/gru_model.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:374c6df9a7c7c64105c3c1b3e8a3d87cd688a84101599116ae44d1a272710b61
3
+ size 25902232
input/emotions.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a51d6be460818bd6dd39ead707d7f2228c0ae8c4e88f8b79957e8853a0d5fdfa
3
+ size 51200113