keras.utils.to_categorical() - name keras not defined

本文介绍如何使用TensorFlow和Keras库将数据转换为多类别编码,重点在于y_train和y_test的one-hot编码技巧,适合初学者理解深度学习数据准备流程。
部署运行你感兴趣的模型镜像

解决方案

import tensorflow as tf
from keras import utils as np_utils 

 y_train =  tf.keras.utils.to_categorical(y_train, num_classes)
 y_test = tf.keras.utils.to_categorical(y_test, num_classes)

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

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
最新发布
11-19
41:06.997458: W tensorflow/core/framework/op_kernel.cc:1828] OP_REQUIRES failed at sparse_xent_op.cc:103 : INVALID_ARGUMENT: Received a label value of 13 which is outside the valid range of [0, 10). Label values: 6 11 6 6 4 10 6 4 0 5 10 8 8 13 4 1 8 4 3 8 5 6 2 3 7 6 5 6 0 5 5 10 Traceback (most recent call last): File "D:\rgzn_project\train.py", line 482, in <module> history = model.fit(x_train, y_train-1, batch_size=32, epochs=50, File "D:\python_project\python\.venv\lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "D:\python_project\python\.venv\lib\site-packages\tensorflow\python\eager\execute.py", line 53, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error: Detected at node 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' defined at (most recent call last): File "D:\rgzn_project\train.py", line 482, in <module> history = model.fit(x_train, y_train-1, batch_size=32, epochs=50, File "D:\python_project\python\.venv\lib\site-packages\keras\src\utils\traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1742, in fit tmp_logs = self.train_function(iterator) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1338, in train_function return step_function(self, iterator) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1322, in step_function outputs = model.distribute_strategy.run(run_step, args=(data,)) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1303, in run_step outputs = model.train_step(data) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1081, in train_step loss = self.compute_loss(x, y, y_pred, sample_weight) File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\training.py", line 1139, in compute_loss return self.compiled_loss( File "D:\python_project\python\.venv\lib\site-packages\keras\src\engine\compile_utils.py", line 265, in __call__ loss_value = loss_obj(y_t, y_p, sample_weight=sw) File "D:\python_project\python\.venv\lib\site-packages\keras\src\losses.py", line 142, in __call__ losses = call_fn(y_true, y_pred) File "D:\python_project\python\.venv\lib\site-packages\keras\src\losses.py", line 268, in call return ag_fn(y_true, y_pred, **self._fn_kwargs) File "D:\python_project\python\.venv\lib\site-packages\keras\src\losses.py", line 2354, in sparse_categorical_crossentropy return backend.sparse_categorical_crossentropy( File "D:\python_project\python\.venv\lib\site-packages\keras\src\backend.py", line 5762, in sparse_categorical_crossentropy res = tf.nn.sparse_softmax_cross_entropy_with_logits( Node: 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' Received a label value of 13 which is outside the valid range of [0, 10). Label values: 6 11 6 6 4 10 6 4 0 5 10 8 8 13 4 1 8 4 3 8 5 6 2 3 7 6 5 6 0 5 5 10 [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_11610]
06-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值