import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import tensorflow
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.layers import Embedding
from tensorflow.keras.layers import LSTM
tf.keras.backend.clear_session()
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn import datasets, tree, linear_model, svm
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
import seaborn as sns
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
data = pd.read_csv("./emotions.csv")
# Seprarting Positive,Neagtive and Neutral dataframes for plortting
pos = data.loc[data["label"] == "POSITIVE"]
sample_pos = pos.loc[2, 'fft_0_b':'fft_749_b']
neg = data.loc[data["label"] == "NEGATIVE"]
sample_neg = neg.loc[0, 'fft_0_b':'fft_749_b']
neu = data.loc[data["label"] == "NEUTRAL"]
sample_neu = neu.loc[1, 'fft_0_b':'fft_749_b']
#plottintg Dataframe distribution
plt.figure(figsize=(25,7))
plt.title("Data distribution of Emotions")
plt.style.use('fivethirtyeight')
sns.countplot(x='label', data=data)
plt.show()
#Plotting Positive DataFrame
plt.figure(figsize=(16, 10))
plt.plot(range(len(sample_pos)), sample_pos)
plt.title("Graph of Positive Columns")
plt.show()
'''As we can noticed the most of the Negative Signals are from greater than 600 to and less than than -600'''
#Plotting Negative DataFrame
plt.figure(figsize=(16, 10))
plt.plot(range(len(sample_neg)), sample_neg)
plt.title("Graph of Negative Columns")
plt.show()
#Plotting Neutral DataFrame
plt.figure(figsize=(16, 10))
plt.plot(range(len(sample_neu)), sample_neu)
plt.title("Graph of Neutral Columns")
plt.show()
def Transform_data(data):
#Encoding Lables into numbers
encoding_data = ({'NEUTRAL': 0, 'POSITIVE': 1, 'NEGATIVE': 2} )
data_encoded = data.replace(encoding_data)
#getting brain signals into x variable
x=data_encoded.drop(["label"] ,axis=1)
#getting labels into y variable
y = data_encoded.loc[:,'label'].values
scaler = StandardScaler()
#scaling Brain Signals
scaler.fit(x)
X = scaler.transform(x)
#One hot encoding Labels
Y = to_categorical(y)
return X,Y
#Calling above function and splitting dataset into train and test
X,Y = Transform_data(data)
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 4)
if tf.config.list_physical_devices('GPU'):
print('Using GPU')
with tf.device('/GPU:0'):
# 原代码中的模型创建、编译和训练部分
# ...
# 示例:创建模型
def create_model():
# input layer of model for brain signals
inputs = tf.keras.Input(shape=(x_train.shape[1],))
# Hidden Layer for Brain signal using LSTM(GRU)
expand_dims = tf.expand_dims(inputs, axis=2)
gru = tf.keras.layers.GRU(256, return_sequences=True)(expand_dims)
# Flatten Gru layer into vector form (one Dimensional array)
flatten = tf.keras.layers.Flatten()(gru)
# output latyer of Model
outputs = tf.keras.layers.Dense(3, activation='softmax')(flatten)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
print(model.summary())
return model
# cretaing model
lstmmodel = create_model()
# Compiling model
lstmmodel.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Training and Evaluting model
history = lstmmodel.fit(x_train, y_train, epochs = 10, validation_split=0.1)
loss, acc = lstmmodel.evaluate(x_test, y_test)
# Loss and Accuracy of model on Testiong Dataset
print(f"Loss on testing: {loss*100}",f"\nAccuracy on Training: {acc*100}")
# predicting model on test set for plotting Confusion Matrix
pred = lstmmodel.predict(x_test)
else:
print('Using CPU')
# Creation of Function of Confusion Matrix
def plot_confusion_matrix(cm, names, title='Confusion matrix', cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(data.label.unique()))
plt.xticks(tick_marks, names, rotation=90)
plt.yticks(tick_marks, names)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# after getting prediction checking maximum score prediction to claim which emotion this brain signal belongs to
pred1 = np.argmax(pred, axis=1)
# inversing the one hot encoding
y_test1 = np.argmax(y_test, axis=1)
# printing first 10 Actual and predicted outputs of Test brain signals
print("Predicted: ", pred1[:10])
print("\n")
print("Actual: ", y_test1[:10])
# Plotting Confusion matrix of Lstm Model
cm = confusion_matrix(y_test1, pred1)
np.set_printoptions(precision=2)
print('Confusion matrix, without normalization')
print(cm)
plt.rcParams["figure.figsize"] = (20, 5)
plt.figure()
plot_confusion_matrix(cm, ["Neutral", "Positive", "Negative"])运行后出现Traceback (most recent call last):
File "C:\Users\86139\Desktop\pythonProject1\main.py", line 147, in <module>
pred1 = np.argmax(pred, axis=1)
^^^^
NameError: name 'pred' is not defined
Using CPU,我需要解决问题并使用GPU
最新发布