能够利用tf.keras获取数据集:
时间: 2024-10-25 13:09:56 浏览: 41
在TensorFlow库中,特别是通过tf.keras模块,可以方便地加载和处理各种数据集。Keras提供了一些内置的数据预处理函数,如`tf.keras.utils.image_dataset_from_directory`用于从文件夹加载图像数据,`tf.keras.preprocessing.text.Tokenizer`用于文本序列化,以及`tf.keras.datasets`直接封装了一些经典的数据集如MNIST、CIFAR等。
例如,如果你想要加载MNIST手写数字数据集,你可以这样做:
```python
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
```
对于自定义数据集,通常需要先将其转化为tf.data.Dataset对象,以便于批量化处理和并行计算。这可以通过`tf.data.Dataset.from_tensor_slices`或`tf.data.Dataset.from_generator`等方式完成。
相关问题
dataset = pd.read_csv('cifar_train.csv') #dataset = pd.read_csv('heart.csv') #dataset = pd.read_csv('iris.csuv') #sns.pairplot(dataset.iloc[:, 1:6]) #plt.show() #print(dataset.head()) #shuffled_data = dataset.sample(frac=1) #dataset=shuffled_data #index=[0,1,2,3,4,5,6,7,8,9,10,11,12,13] #dataset.columns=index dataset2=pd.read_csv('test.csv') #X = dataset.iloc[:, :30].values #y = dataset.iloc[:,30].values mm = MinMaxScaler() from sklearn.model_selection import train_test_split #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0) X_train =dataset.iloc[:,1:].values X_test = dataset2.iloc[:,1:].values y_train = dataset.iloc[:,0].values y_test = dataset2.iloc[:,0].values print(y_train) # 进行独热编码 def one_hot_encode_object_array(arr): # 去重获取全部的类别 uniques, ids = np.unique(arr, return_inverse=True) # 返回热编码的结果 return tf.keras.utils.to_categorical(ids, len(uniques)) #train_y_ohe=y_train #test_y_ohe=y_test # 训练集热编码 train_y_ohe = one_hot_encode_object_array(y_train) # 测试集热编码 test_y_ohe = one_hot_encode_object_array(y_test) # 利用sequential方式构建模型 from keras import backend as K def swish(x, beta=1.0): return x * K.sigmoid(beta * x) from keras import regularizers model = tf.keras.models.Sequential([ # 隐藏层1,激活函数是relu,输入大小有input_shape指定 tf.keras.layers.InputLayer(input_shape=(3072,)), # lambda(hanshu, output_shape=None, mask=None, arguments=None), #tf.keras.layers.Lambda(hanshu, output_shape=None, mask=None, arguments=None), tf.keras.layers.Dense(500, activation="relu"), # 隐藏层2,激活函数是relu tf.keras.layers.Dense(500, activation="relu"), # 输出层 tf.keras.layers.Dense(10, activation="softmax") ])
根据你提供的代码,我注意到你使用了 `MinMaxScaler` 对数据进行预处理。这可能导致数据的形状发生变化,进而导致模型输入的形状不匹配。
请确保在对数据进行预处理之前,将数据转换为正确的形状,并对其进行缩放,以便与模型的输入层匹配。
此外,你可能还需要检查以下几点:
1. 数据集的特征列是否正确地分配给 `X_train` 和 `X_test`,并且标签列是否正确地分配给 `y_train` 和 `y_test`。
2. 确保数据集的特征列和标签列的数量与模型定义中的输入层和输出层匹配。例如,如果你使用了3072个特征列和10个输出类别,那么模型定义中的输入层应该是 `(3072,)`,输出层应该是 `(10,)`。
3. 检查数据集中是否存在缺失值或异常值,并根据需要进行处理。
在修复了这些问题后,你的模型定义应该能够正确地与数据进行匹配。如果问题仍然存在,请提供更多关于数据集和模型定义的信息,以便我能够提供更具体的建议。
import numpy import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import os import cv2 as cv from sklearn.model_selection import train_test_split def getImgeAndLabels(path): #存放训练图片 facesSamples = [] #存放图片id ids = [] #存放路径和名称 imagPaths = [] for f in os.listdir(path): #连接文件夹路径和图片名称 result = os.path.join(path,f) #存入 imagPaths.append(result) face_detector = cv.CascadeClassifier(r'D:\pyh\envs\OpenCV\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml') for imagPath in imagPaths: #读取每一种图片 img = cv.imread(imagPath) PIL_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY) #获取每张图片的id 利用os.path.split的方法将路径和名称分割开 id = int(os.path.split(imagPath)[1].split('.')[0]) facesSamples.append(PIL_img) ids.append(id) return facesSamples,ids if __name__ == '__main__': path = './data/' faces,ids = getImgeAndLabels(path) x = np.array(faces,dtype = np.uint8) y = np.array(ids,dtype = np.uint8) x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0) model = tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(112, 92)), #拉平转化为一维数据 tf.keras.layers.Flatten(input_shape=(112,92)), #定义神经网络全连接层,参数是神经元个数以及使用激活函数 tf.keras.layers.Dense(200,activation='relu'), #设置遗忘率 # tf.keras.layers.Dropout(0.2), #定义最终输出(输出10种类别,softmax实现分类的概率分布) tf.keras.layers.Dense(16,activation='softmax') ]) model.compile( optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) print("模型*************") model.fit(x,y,epochs=80) print("成绩***********") model.evaluate(x_test,y_test) class_name = ['u1','u2','u3', 'u4','u5','u6','u7','u8','u9','u10','u11','u12','u13',] predata = cv.imread(r'./data/5.pgm') predata = cv.cvtColor(predata, cv.COLOR_RGB2GRAY) reshaped_data = np.reshape(predata, (1, 112, 92)) #预测一个10以内的数组,他们代表对10种不同服装的可信度 predictions_single = model.predict(reshaped_data) max = numpy.argmax(predictions_single) #在列表中找到最大值 print(class_name[max-1]) plt.imshow(x_test[10],cmap=plt.cm.gray_r) plt.show()
这段代码是一个人脸识别的模型,使用了 TensorFlow 和 OpenCV 库。首先通过 getImgeAndLabels 函数获取训练数据集,然后使用 train_test_split 函数将数据集分成训练集和测试集。接着使用 Sequential 模型定义了一个神经网络模型,包含了一个输入层、一个全连接层和一个输出层,其中激活函数采用了 relu 和 softmax。使用 compile 函数对模型进行编译,指定了优化器、损失函数和评价指标。然后使用 fit 函数对模型进行训练,使用 evaluate 函数对模型进行测试。最后使用预测函数 predict 进行预测并输出结果。
阅读全文
相关推荐
















