from keras.datasets import cifar10 import matplotlib.pyplot as plt from keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense,Dropout,Flatten (train_image,train_label),(test_image,test_label)=cifar10.load_data() dict={0:'airplane',1:'automobile',2:'bird',3:'cat',4:'deer',5:'dog',6:'frog',7:'horse',8:'ship',9:'truck'} for i in range(0,12): plt.subplot(3,4,i+1) plt.imshow(train_image[i]) plt.title(dict[train_label[i,0]],fontsize=8) #plt.show() #步骤二:数据预处理 Train_image=train_image.astype('float32')/255 Test_image=test_image.astype('float32')/255 Train_Onehot=np_utils.to_categorical(train_label) Train_Onehot=np_utils.to_categorical(test_label) #步骤三:建立模型 model=Sequential() model.add(Conv2D(filters=32, kernel_size=(3,3), input_shape=(32,32,3), padding='same', activation='relu', )) model.add(Dropout(0.25)) model.add(MaxPooling2D( pool_size=(2,2))) model.add(Conv2D(filters=64, kernel_size=(3,3), padding='same', activation='relu', )) #添加dropout,避免过拟合 model.add(Dropout(0.25)) #添加池化层2 model.add(MaxPooling2D(pool_size=(2,2))) #添加平坦层 model.add(Flatten()) #添加dropout model.add(Dropout(0.25)) #添加隐藏层 model.add(Dense(1024,activation='relu')) #添加dropout model.add(Dropout(0.25)) #输出层 model.add(Dense(units=10,activation='softmax')) #打印模型 print(model.summary()) #步骤四:模型训练 model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'],) #训练模型 #epoch:训练5个周期 #batch_size:每一批次128项数据 #verbose=2:显示训练过程 #validation_split=0.2. model.fit(x=Train_image, y=Train_Onehot, batch_size=128, epochs=10, verbose=2, validation_split=0.2, ) model.save('cifar10.h5')出现了Input arrays should have the same number of samples as target arrays. Found 50000 input samples and 10000 target samples.错误,我应该怎么改
时间: 2023-12-30 22:04:13 浏览: 158
在这段代码中,似乎有一个问题,就是在数据预处理的步骤中,将测试集的目标变量也转换为了one-hot编码,导致训练集和测试集的目标变量数量不匹配。为了解决这个问题,你需要将以下两行代码中的 "Train_Onehot" 改为 "Test_Onehot":
```
Train_Onehot=np_utils.to_categorical(train_label)
Train_Onehot=np_utils.to_categorical(test_label)
```
修改为:
```
Train_Onehot=np_utils.to_categorical(train_label)
Test_Onehot=np_utils.to_categorical(test_label)
```
这样就可以将测试集的目标变量正确地转换为one-hot编码,从而避免 "Input arrays should have the same number of samples as target arrays." 的错误。
相关问题
import numpy as np import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist from keras import backend as K from keras.optimizers import Adam import skfuzzy as fuzz import pandas as pd from sklearn.model_selection import train_test_split # 绘制损失曲线 import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score data = pd.read_excel(r"D:\pythonProject60\filtered_data1.xlsx") # 读取数据文件 # Split data into input and output variables X = data.iloc[:, :-1].values y = data.iloc[:, -1].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 导入MNIST数据集 # 数据预处理 y_train = np_utils.to_categorical(y_train, 3) y_test = np_utils.to_categorical(y_test, 3) # 创建DNFN模型 model = Sequential() model.add(Dense(64, input_shape=(11,), activation='relu')) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(3, activation='softmax')) # 编译模型 model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy']) # 训练模型 history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128) # 使用DNFN模型进行预测 y_pred = model.predict(X_test) y_pred= np.argmax(y_pred, axis=1) print(y_pred) # 计算模糊分类 fuzzy_pred = [] for i in range(len(y_pred)): fuzzy_class = np.zeros((3,)) fuzzy_class[y_pred[i]] = 1.0 fuzzy_pred.append(fuzzy_class) fuzzy_pred = np.array(fuzzy_pred) print(fuzzy_pred)获得其运行时间
抱歉,我无法获得该代码的运行时间,因为您没有在代码中包含计时器或时间测量的代码。您可以使用Python的time模块来计算代码的运行时间。例如,您可以在代码的开始和结束位置添加以下代码:
```
import time
start_time = time.time()
# Your code here
end_time = time.time()
print("Total time taken: ", end_time - start_time, "seconds")
```
这将打印代码的总运行时间,以秒为单位。
下面的代码哪里有问题,帮我改一下from __future__ import print_function import numpy as np import tensorflow import keras from keras.models import Sequential from keras.layers import Dense,Dropout,Flatten from keras.layers import Conv2D,MaxPooling2D from keras import backend as K import tensorflow as tf import datetime import os np.random.seed(0) from sklearn.model_selection import train_test_split from PIL import Image import matplotlib.pyplot as plt from keras.datasets import mnist images = [] labels = [] (x_train,y_train),(x_test,y_test)=mnist.load_data() X = np.array(images) print (X.shape) y = np.array(list(map(int, labels))) print (y.shape) x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0) print (x_train.shape) print (x_test.shape) print (y_train.shape) print (y_test.shape) ############################ ########## batch_size = 20 num_classes = 4 learning_rate = 0.0001 epochs = 10 img_rows,img_cols = 32 , 32 if K.image_data_format() =='channels_first': x_train =x_train.reshape(x_train.shape[0],1,img_rows,img_cols) x_test = x_test.reshape(x_test.shape[0],1,img_rows,img_cols) input_shape = (1,img_rows,img_cols) else: x_train = x_train.reshape(x_train.shape[0],img_rows,img_cols,1) x_test = x_test.reshape(x_test.shape[0],img_rows,img_cols,1) input_shape =(img_rows,img_cols,1) x_train =x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:',x_train.shape) print(x_train.shape[0],'train samples') print(x_test.shape[0],'test samples')
代码中存在以下问题:
1. 变量 images 和 labels 没有被赋值,而后面却使用了它们来构造 X 和 y,导致 X 和 y 的值都为空。
2. 导入的 mnist 数据集没有被使用,而是使用了未定义的 images 和 labels,需要将其替换为 mnist 数据集。
3. input_shape 的值应该是三元组 (img_rows, img_cols, 1),而代码中缺少了最后一个 1。
4. 在 if K.image_data_format() =='channels_first': 分支中,x_train 和 x_test 被改变了形状,但 y_train 和 y_test 却没有被改变,需要将其同步修改。
下面是修改后的代码:
```
from __future__ import print_function
import numpy as np
import tensorflow
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import tensorflow as tf
import datetime
import os
np.random.seed(0)
from sklearn.model_selection import train_test_split
from PIL import Image
import matplotlib.pyplot as plt
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape)
print(y_train.shape)
############################
##########
batch_size = 20
num_classes = 10
learning_rate = 0.0001
epochs = 10
img_rows, img_cols = 32, 32
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (img_rows, img_cols, 1)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('input_shape:', input_shape)
```
阅读全文