关于Keras.model的fit()方法中y参数设置的训练问题

keras中fit方法解释y参数可输入字典映射,请问输入格式应该是怎么样的呢?
keras.model.fit()方法源码解释如下:

y: Numpy array of target (label) data
    (if the model has a single output),
    or list of Numpy arrays (if the model has multiple outputs).
    If output layers in the model are named, you can also pass a
    dictionary mapping output names to Numpy arrays.

目前model.fit()参数设置如下:

self.model.fit(dataset.train_images,
                            dataset.train_labels,
                            batch_size=batch_size,
                            epochs=nb_epoch,
                            validation_data=(dataset.valid_images, dataset.valid_labels),
                            callbacks=callbacks,
                            shuffle=True)

其中dataset.train_images 的shape为:
图片说明

传入的标签字典dataset.train_labels的形式为:
图片说明

报错图片:
图片说明

请问应该如何设置fit()方法中的y参数才能让模型训练出来预测时输出对应的映射名字。

1个回答

图像训练的时候,你的目标输出是什么?是‘George_W_Bush’吗?后面的array是one-hot独热编码吗?
如果是的话新建立一个list提取出你的字典的key值,然后用这个新建立的list给model去fit

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
keras model.fit函数报错,输入参数shape维度不正确,如何修正

使用函数 ``` model.fit(x=images, y=labels, validation_split=0.1, batch_size=batch_size, epochs=n_epochs, callbacks=callbacks, shuffle=True) ``` 由于我的训练集中image是灰色图片,所以images的shape为(2, 28, 28),导致报错Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (2, 28, 28) ,请问该如何处理

keras model.fit_generator训练完一个epoch之后无法加载训练集怎么处理?

1、在训练神经网络的过程中遇到了训练完一个epoch之后无法继续训练的问题,具体问题截图如下 ![图片说明](https://img-ask.csdn.net/upload/202002/08/1581151633_972155.png) 数据生成的代码如下 ``` def GET_DATASET_SHUFFLE(train_x, train_y, batch_size): #random.shuffle(X_samples) batch_num = int(len(train_x) / batch_size) max_len = batch_num * batch_size X_samples = np.array(train_x[0:max_len]) Y_samples = np.array(train_y[0:max_len]) X_batches = np.split(X_samples, batch_num) Y_batches = np.split(Y_samples, batch_num) for i in range(batch_num): x = np.array(list(map(load_image, X_batches[i]))) y = np.array(list(map(load_label, Y_batches[i]))) yield x, y ``` 想要向各位大神请教一下,刚刚接触这个不是太懂

我的keras的model.fit写在一个loop里,callback每一个epoch会生成一个events文件,如何处理这种问题?

if resume: # creates a generic neural network architecture model = Sequential() # hidden layer takes a pre-processed frame as input, and has 200 units model.add(Dense(units=200,input_dim=80*80, activation='relu', kernel_initializer='glorot_uniform')) # output layer model.add(Dense(units=1, activation='sigmoid', kernel_initializer='RandomNormal')) # compile the model using traditional Machine Learning losses and optimizers model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #print model model.summary() if os.path.isfile('Basic_Rl_weights.h5'): #load pre-trained model weight print("loading previous weights") model.load_weights('Basic_Rl_weights.h5') else : # creates a generic neural network architecture model = Sequential() # hidden layer takes a pre-processed frame as input, and has 200 units model.add(Dense(units=200,input_dim=80*80, activation='relu', kernel_initializer='glorot_uniform')) # output layer model.add(Dense(units=1, activation='sigmoid', kernel_initializer='RandomNormal')) # compile the model using traditional Machine Learning losses and optimizers model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #print model model.summary() #save model # model.save_weights('my_model_weights.h5') log_dir = './log' + datetime.now().strftime("%Y%m%d-%H%M%S") + "/" callbacks = callbacks.TensorBoard(log_dir=log_dir, histogram_freq=0, write_graph=True, write_images=True) # gym initialization env = gym.make("Pong-v0") observation = env.reset() prev_x = None # used in computing the difference frame running_reward = None # initialization of variables used in the main loop x_train, y_train, rewards = [],[],[] reward_sum = 0 episode_number = 0 # main loop while True: if render : env.render() # preprocess the observation, set input as difference between images cur_x = prepro(observation) # i=np.expand_dims(cur_x,axis=0) # print(i.shape) # print(cur_x.shape) if prev_x is not None : x = cur_x - prev_x else: x = np.zeros(Input_dim) # print(x.shape) # print(np.expand_dims(cur_x,axis=0).shape) prev_x = cur_x # forward the policy network and sample action according to the proba distribution # two ways to calculate returned probability # print(x.shape) prob = model.predict(np.expand_dims(x, axis=1).T) # aprob = model.predict(np.expand_dims(x, axis=1).T) if np.random.uniform() < prob: action = action_up else : action = action_down # 0 and 1 labels( a fake label in order to achive back propagation algorithm) if action == 2: y = 1 else: y = 0 # log the input and label to train later x_train.append(x) y_train.append(y) # do one step in our environment observation, reward, done, info = env.step(action) rewards.append(reward) reward_sum += reward # end of an episode if done: print('At the end of episode', episode_number, 'the total reward was :', reward_sum) # increment episode number episode_number += 1 # training # history = LossHistory() model.fit(x=np.vstack(x_train), y=np.vstack(y_train), verbose=1, sample_weight=discount_rewards(rewards), callbacks=[callbacks]) if episode_number % 100 == 0: model.save_weights('Basic_Rl_weights' + datetime.now().strftime("%Y%m%d-%H%M%S") + '.h5') # Log the reward running_reward = reward_sum if running_reward is None else running_reward * 0.99 + reward_sum * 0.01 # if episode_number % 10 == 0: tflog('running_reward', running_reward, custom_dir=log_dir) # Reinitialization x_train, y_train, rewards = [],[],[] observation = env.reset() reward_sum = 0 prev_x = None ``` ```

keras多GPU训练,其中一块无法调用

已经按multi_gpu_model进行了设置 但是运行的时候还是只能调用一个GPU,另一张计算卡完全没用,是什么原因呢? ``` from keras.utils import multi_gpu_model ... model = build_model() optimizer = keras.optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-06) model_parallel=multi_gpu_model(model,2) model_parallel.compile(loss='mse', optimizer=optimizer, metrics=['mae']) ... history = model_parallel.fit(train_data, y_train, epochs=EPOCHS, validation_split=0.2, verbose=1,callbacks=[PrintDot()]) ``` ![图片说明](https://img-ask.csdn.net/upload/201911/15/1573813427_19477.jpg) ![图片说明](https://img-ask.csdn.net/upload/201911/15/1573813436_730710.jpg)

使用Keras找不到tensorflow

程序代码 #-*- coding: utf-8 -*- #使用神经网络算法预测销量高低 import pandas as pd #参数初始化 inputfile = 'D:/python/chapter5/demo/data/sales_data.xls' data = pd.read_excel(inputfile, index_col = u'序号') #导入数据 #数据是类别标签,要将它转换为数据 #用1来表示“好”、“是”、“高”这三个属性,用0来表示“坏”、“否”、“低” data[data == u'好'] = 1 data[data == u'是'] = 1 data[data == u'高'] = 1 data[data != 1] = 0 x = data.iloc[:,:3].as_matrix().astype(int) y = data.iloc[:,3].as_matrix().astype(int) from keras.models import Sequential from keras.layers.core import Dense, Activation model = Sequential() #建立模型 model.add(Dense(input_dim = 3, output_dim = 10)) model.add(Activation('relu')) #用relu函数作为激活函数,能够大幅提供准确度 model.add(Dense(input_dim = 10, output_dim = 1)) model.add(Activation('sigmoid')) #由于是0-1输出,用sigmoid函数作为激活函数 model.compile(loss = 'binary_crossentropy', optimizer = 'adam', class_mode = 'binary') #编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary #另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。 #求解方法我们指定用adam,还有sgd、rmsprop等可选 model.fit(x, y, nb_epoch = 1000, batch_size = 10) #训练模型,学习一千次 yp = model.predict_classes(x).reshape(len(y)) #分类预测 from cm_plot import * #导入自行编写的混淆矩阵可视化函数 cm_plot(y,yp).show() #显示混淆矩阵可视化结果 错误提示 Using TensorFlow backend. Traceback (most recent call last): File "D:\python\chapter5\demo\code\5-3_neural_network.py", line 19, in <module> from keras.models import Sequential File "C:\Python27\lib\site-packages\keras\__init__.py", line 3, in <module> from . import utils File "C:\Python27\lib\site-packages\keras\utils\__init__.py", line 6, in <module> from . import conv_utils File "C:\Python27\lib\site-packages\keras\utils\conv_utils.py", line 3, in <module> from .. import backend as K File "C:\Python27\lib\site-packages\keras\backend\__init__.py", line 83, in <module> from .tensorflow_backend import * File "C:\Python27\lib\site-packages\keras\backend\tensorflow_backend.py", line 1, in <module> import tensorflow as tf ImportError: No module named tensorflow

keras 训练网络时出现ValueError

rt 使用keras中的model.fit函数进行训练时出现错误:ValueError: None values not supported. 错误信息如下: ``` File "C:/Users/Desktop/MNISTpractice/mnist.py", line 93, in <module> model.fit(x_train,y_train, epochs=2, callbacks=callback_list,validation_data=(x_val,y_val)) File "C:\Anaconda3\lib\site-packages\keras\engine\training.py", line 1575, in fit self._make_train_function() File "C:\Anaconda3\lib\site-packages\keras\engine\training.py", line 960, in _make_train_function loss=self.total_loss) File "C:\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper return func(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\keras\optimizers.py", line 432, in get_updates m_t = (self.beta_1 * m) + (1. - self.beta_1) * g File "C:\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 820, in binary_op_wrapper y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y") File "C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 639, in convert_to_tensor as_ref=False) File "C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 704, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "C:\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 113, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "C:\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 102, in constant tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "C:\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 360, in make_tensor_proto raise ValueError("None values not supported.") ValueError: None values not supported. ```

keras中model.evaluate()报错:'numpy.float64' object is not iterable

``` x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.25) mean = x_train.mean(axis=0) std = x_train.std(axis=0) train_data = (x_train - mean) / std test_data = (x_test - mean) / std model = Sequential([Dense(64, input_shape=(6,)), Activation('relu'), Dense(32), Activation('relu'), Dense(1)]) sgd = keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd) k = model.fit [loss, sgd] = model.evaluate(test_data, y_test, verbose=1) ``` 最后一步不知道哪出了问题。。test_data, y_test都是dataframe啊 TypeError Traceback (most recent call last) <ipython-input-29-3b0767a3c446> in <module> ----> 1 [loss, mse] = model.evaluate(test_data, y_test, verbose=1) TypeError: 'numpy.float64' object is not iterable

在学习人脸识别运用keras的过程中出现了问题

本人在尝试学习"http://www.cnblogs.com/neo-T/p/6477378.html" 此博客提供的人脸识别代码 遇到了以下问题,不知该怎么解决 ``` WARNING:tensorflow:Variable *= will be deprecated. Use variable.assign_mul if you want assignment to the variable value or 'x = x * y' if you want a new python Tensor object. Epoch 1/10 Traceback (most recent call last): File "E:/python/python3.64/python代码练习/人脸识别/face_train_use_keras.py", line 189, in <module> model.train(dataset) File "E:/python/python3.64/python代码练习/人脸识别/face_train_use_keras.py", line 179, in train validation_data=(dataset.valid_images, dataset.valid_labels)) File "E:\python\anaconda\anaconda\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "E:\python\anaconda\anaconda\lib\site-packages\keras\models.py", line 1315, in fit_generator initial_epoch=initial_epoch) File "E:\python\anaconda\anaconda\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "E:\python\anaconda\anaconda\lib\site-packages\keras\engine\training.py", line 2268, in fit_generator callbacks.on_epoch_end(epoch, epoch_logs) File "E:\python\anaconda\anaconda\lib\site-packages\keras\callbacks.py", line 77, in on_epoch_end callback.on_epoch_end(epoch, logs) File "E:\python\anaconda\anaconda\lib\site-packages\keras\callbacks.py", line 339, in on_epoch_end self.progbar.update(self.seen, self.log_values) AttributeError: 'ProgbarLogger' object has no attribute 'log_values' ``` 我清楚ProgbarLogger内没有log_values的属性的意思,但是因为刚开始接触,不知道应怎样改动

为什么同样的问题用Tensorflow和keras实现结果不一样?

**cifar-10分类问题,同样的模型结构以及损失函数还有学习率参数等超参数,分别用TensorFlow和keras实现。 20个epochs后在测试集上进行预测,准确率总是差好几个百分点,不知道问题出在哪里?代码如下: 这个是TF的代码:** import tensorflow as tf import numpy as np import pickle as pk tf.reset_default_graph() batch_size = 64 test_size = 10000 img_size = 32 num_classes = 10 training_epochs = 10 test_size=200 ############################################################################### def unpickle(filename): '''解压数据''' with open(filename, 'rb') as f: d = pk.load(f, encoding='latin1') return d def onehot(labels): '''one-hot 编码''' n_sample = len(labels) n_class = max(labels) + 1 onehot_labels = np.zeros((n_sample, n_class)) onehot_labels[np.arange(n_sample), labels] = 1 return onehot_labels # 训练数据集 data1 = unpickle('data_batch_1') data2 = unpickle('data_batch_2') data3 = unpickle('data_batch_3') data4 = unpickle('data_batch_4') data5 = unpickle('data_batch_5') X_train = np.concatenate((data1['data'], data2['data'], data3['data'], data4['data'], data5['data']), axis=0)/255.0 y_train = np.concatenate((data1['labels'], data2['labels'], data3['labels'], data4['labels'], data5['labels']), axis=0) y_train = onehot(y_train) # 测试数据集 test = unpickle('test_batch') X_test = test['data']/255.0 y_test = onehot(test['labels']) del test,data1,data2,data3,data4,data5 ############################################################################### w = tf.Variable(tf.random_normal([5, 5, 3, 32], stddev=0.01)) w_c= tf.Variable(tf.random_normal([32* 16* 16, 512], stddev=0.1)) w_o =tf.Variable(tf.random_normal([512, num_classes], stddev=0.1)) def init_bias(shape): return tf.Variable(tf.constant(0.0, shape=shape)) b=init_bias([32]) b_c=init_bias([512]) b_o=init_bias([10]) def model(X, w, w_c,w_o, p_keep_conv, p_keep_hidden,b,b_c,b_o): conv1 = tf.nn.conv2d(X, w,strides=[1, 1, 1, 1],padding='SAME')#32x32x32 conv1=tf.nn.bias_add(conv1,b) conv1 = tf.nn.relu(conv1) conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')#16x16x32 conv1 = tf.nn.dropout(conv1, p_keep_conv) FC_layer = tf.reshape(conv1, [-1, 32 * 16 * 16]) out_layer=tf.matmul(FC_layer, w_c)+b_c out_layer=tf.nn.relu(out_layer) out_layer = tf.nn.dropout(out_layer, p_keep_hidden) result = tf.matmul(out_layer, w_o)+b_o return result trX, trY, teX, teY = X_train,y_train,X_test,y_test trX = trX.reshape(-1, img_size, img_size, 3) teX = teX.reshape(-1, img_size, img_size, 3) X = tf.placeholder("float", [None, img_size, img_size, 3]) Y = tf.placeholder("float", [None, num_classes]) p_keep_conv = tf.placeholder("float") p_keep_hidden = tf.placeholder("float") py_x = model(X, w, w_c,w_o, p_keep_conv, p_keep_hidden,b,b_c,b_o) Y_ = tf.nn.softmax_cross_entropy_with_logits_v2(logits=py_x, labels=Y) cost = tf.reduce_mean(Y_) optimizer = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) predict_op = tf.argmax(py_x, 1) with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(training_epochs): training_batch = zip(range(0, len(trX),batch_size),range(batch_size, len(trX)+1,batch_size)) perm=np.arange(len(trX)) np.random.shuffle(perm) trX=trX[perm] trY=trY[perm] for start, end in training_batch: sess.run(optimizer, feed_dict={X: trX[start:end],Y: trY[start:end],p_keep_conv:0.75,p_keep_hidden: 0.5}) test_batch = zip(range(0, len(teX),test_size),range(test_size, len(teX)+1,test_size)) accuracyResult=0 for start, end in test_batch: accuracyResult=accuracyResult+sum(np.argmax(teY[start:end], axis=1) ==sess.run(predict_op, feed_dict={X: teX[start:end],Y: teY[start:end],p_keep_conv: 1,p_keep_hidden: 1})) print(i, accuracyResult/10000) **这个是keras代码:** from keras import initializers from keras.datasets import cifar10 from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.optimizers import SGD, Adam, RMSprop #import matplotlib.pyplot as plt # CIFAR_10 is a set of 60K images 32x32 pixels on 3 channels IMG_CHANNELS = 3 IMG_ROWS = 32 IMG_COLS = 32 #constant BATCH_SIZE = 64 NB_EPOCH = 10 NB_CLASSES = 10 VERBOSE = 1 VALIDATION_SPLIT = 0 OPTIM = RMSprop() #load dataset (X_train, y_train), (X_test, y_test) = cifar10.load_data() #print('X_train shape:', X_train.shape) #print(X_train.shape[0], 'train samples') #print(X_test.shape[0], 'test samples') # convert to categorical Y_train = np_utils.to_categorical(y_train, NB_CLASSES) Y_test = np_utils.to_categorical(y_test, NB_CLASSES) # float and normalization X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 # network model = Sequential() model.add(Conv2D(32, (3, 3), padding='same',input_shape=(IMG_ROWS, IMG_COLS, IMG_CHANNELS),kernel_initializer=initializers.random_normal(stddev=0.01),bias_initializer=initializers.Zeros())) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) #0<参数<1才会有用 model.add(Flatten()) model.add(Dense(512,kernel_initializer=initializers.random_normal(stddev=0.1),bias_initializer=initializers.Zeros())) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(NB_CLASSES,kernel_initializer=initializers.random_normal(stddev=0.1),bias_initializer=initializers.Zeros())) model.add(Activation('softmax')) model.summary() # train model.compile(loss='categorical_crossentropy', optimizer=OPTIM,metrics=['accuracy']) model.fit(X_train, Y_train, batch_size=BATCH_SIZE,epochs=NB_EPOCH, validation_split=VALIDATION_SPLIT,verbose=VERBOSE) score = model.evaluate(X_test, Y_test,batch_size=200, verbose=VERBOSE) print("Test score:", score[0]) print('Test accuracy:', score[1])

做keras的可视化时utils.apply_modifications出错

**#(1)用mnist文件生成了model.h5文件:** import numpy as np import keras from keras.datasets import mnist from keras.models import Sequential,Model from keras.layers import Dense,Dropout,Flatten,Activation,Input from keras.layers import Conv2D,MaxPooling2D from keras import backend as K batch_size=128 num_classes=10 epochs=5 #定义图像的长宽 img_rows,img_cols=28,28 #加载mnist数据集 (x_train,y_train),(x_test,y_test)=mnist.load_data() #定义图像的格式 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') y_train=keras.utils.to_categorical(y_train,num_classes) y_test=keras.utils.to_categorical(y_test,num_classes) #开始DNN网络 model=Sequential() model.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=input_shape)) model.add(Conv2D(54,(3,3),activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128,activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes,activation='softmax',name='preds')) model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy']) model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test,y_test)) score=model.evaluate(x_test,y_test,verbose=0) print('Test loss:',score[0]) print('Test accuracy:',score[1]) model.save('model.h5') **#(2)用生成的mnist文件做测试:** from keras.models import load_model from vis.utils import utils from keras import activations model=load_model('model.h5') layer_idx=utils.find_layer_idx(model,'preds') model.layers[layer_idx].activation=activations.linear model = utils.apply_modifications(model) 报错:FileNotFoundError: [WinError 3] 系统找不到指定的路径。: '/tmp/curzzxs_.h5'

基于keras,使用imagedatagenerator.flow函数读入数据,训练集ACC极低

在做字符识别的神经网络,数据集是用序号标好名称的图片,标签取图片的文件名。想用Imagedatagenrator 函数和flow函数,增加样本的泛化性,然后生成数据传入网络,可是这样acc=1/类别数,基本为零。请问哪里出了问题 ``` datagen = ImageDataGenerator( width_shift_range=0.1, height_shift_range=0.1 ) def read_train_image(self, name): myimg = Image.open(name).convert('RGB') return np.array(myimg) def train(self): #训练集 train_img_list = [] train_label_list = [] #测试集 test_img_list = [] test_label_list = [] for file in os.listdir('train'): files_img_in_array = self.read_train_image(name='train/' + file) train_img_list.append(files_img_in_array) # Image list add up train_label_list.append(int(file.split('_')[0])) # lable list addup for file in os.listdir('test'): files_img_in_array = self.read_train_image(name='test/' + file) test_img_list.append(files_img_in_array) # Image list add up test_label_list.append(int(file.split('_')[0])) # lable list addup train_img_list = np.array(train_img_list) train_label_list = np.array(train_label_list) test_img_list = np.array(train_img_list) test_label_list = np.array(train_label_list) train_label_list = np_utils.to_categorical(train_label_list, 5788) test_label_list = np_utils.to_categorical(test_label_list, 5788) train_img_list = train_img_list.astype('float32') test_img_list = test_img_list.astype('float32') test_img_list /= 255.0 train_img_list /= 255.0 ``` 这是图片数据的处理,图片和标签都存到list里。下面是用fit_genrator训练 ``` model.fit_generator( self.datagen.flow(x=train_img_list, y=train_label_list, batch_size=2), samples_per_epoch=len(train_img_list), epochs=10, validation_data=(test_img_list,test_label_list), ) ```

keras框架的数据输入维度问题

x = np.arange(20) 创建一个一维数组shape是(20,),在keras里,如果直接输入神经网络的话,那么输入神经元是20吧? 但是如果x= x.reshape((1, 20))或者x=x.reshape((20,1))就是把原有的一维数组看成一个输入,reshape后的值输入神经网络就是一个神经元吧?上述二者的reshape是不是输入是等价的?

self.model_generator()

为什么我用Keras里,self.model_generator()之后去loss值 ,只能得到最后一个loss值,而不是全部的loss。 这个函数是定义在类中的 ![图片说明](https://img-ask.csdn.net/upload/202004/13/1586764486_1535.jpg)

tf.keras 关于 胶囊网络 capsule的问题

``` from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer from tensorflow.keras import activations from tensorflow.keras import utils from tensorflow.keras.models import Model from tensorflow.keras.layers import * from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.callbacks import TensorBoard import mnist import tensorflow batch_size = 128 num_classes = 10 epochs = 20 """ 压缩函数,我们使用0.5替代hinton论文中的1,如果是1,所有的向量的范数都将被缩小。 如果是0.5,小于0.5的范数将缩小,大于0.5的将被放大 """ def squash(x, axis=-1): s_quared_norm = K.sum(K.square(x), axis, keepdims=True) + K.epsilon() scale = K.sqrt(s_quared_norm) / (0.5 + s_quared_norm) result = scale * x return result # 定义我们自己的softmax函数,而不是K.softmax.因为K.softmax不能指定轴 def softmax(x, axis=-1): ex = K.exp(x - K.max(x, axis=axis, keepdims=True)) result = ex / K.sum(ex, axis=axis, keepdims=True) return result # 定义边缘损失,输入y_true, p_pred,返回分数,传入即可fit时候即可 def margin_loss(y_true, y_pred): lamb, margin = 0.5, 0.1 result = K.sum(y_true * K.square(K.relu(1 - margin -y_pred)) + lamb * (1-y_true) * K.square(K.relu(y_pred - margin)), axis=-1) return result class Capsule(Layer): """编写自己的Keras层需要重写3个方法以及初始化方法 1.build(input_shape):这是你定义权重的地方。 这个方法必须设self.built = True,可以通过调用super([Layer], self).build()完成。 2.call(x):这里是编写层的功能逻辑的地方。 你只需要关注传入call的第一个参数:输入张量,除非你希望你的层支持masking。 3.compute_output_shape(input_shape): 如果你的层更改了输入张量的形状,你应该在这里定义形状变化的逻辑,这让Keras能够自动推断各层的形状。 4.初始化方法,你的神经层需要接受的参数 """ def __init__(self, num_capsule, dim_capsule, routings=3, share_weights=True, activation='squash', **kwargs): super(Capsule, self).__init__(**kwargs) # Capsule继承**kwargs参数 self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.share_weights = share_weights if activation == 'squash': self.activation = squash else: self.activation = activation.get(activation) # 得到激活函数 # 定义权重 def build(self, input_shape): input_dim_capsule = input_shape[-1] if self.share_weights: # 自定义权重 self.kernel = self.add_weight( name='capsule_kernel', shape=(1, input_dim_capsule, self.num_capsule * self.dim_capsule), initializer='glorot_uniform', trainable=True) else: input_num_capsule = input_shape[-2] self.kernel = self.add_weight( name='capsule_kernel', shape=(input_num_capsule, input_dim_capsule, self.num_capsule * self.dim_capsule), initializer='glorot_uniform', trainable=True) super(Capsule, self).build(input_shape) # 必须继承Layer的build方法 # 层的功能逻辑(核心) def call(self, inputs): if self.share_weights: hat_inputs = K.conv1d(inputs, self.kernel) else: hat_inputs = K.local_conv1d(inputs, self.kernel, [1], [1]) batch_size = K.shape(inputs)[0] input_num_capsule = K.shape(inputs)[1] hat_inputs = K.reshape(hat_inputs, (batch_size, input_num_capsule, self.num_capsule, self.dim_capsule)) hat_inputs = K.permute_dimensions(hat_inputs, (0, 2, 1, 3)) b = K.zeros_like(hat_inputs[:, :, :, 0]) for i in range(self.routings): c = softmax(b, 1) o = self.activation(K.batch_dot(c, hat_inputs, [2, 2])) if K.backend() == 'theano': o = K.sum(o, axis=1) if i < self.routings-1: b += K.batch_dot(o, hat_inputs, [2, 3]) if K.backend() == 'theano': o = K.sum(o, axis=1) return o def compute_output_shape(self, input_shape): # 自动推断shape return (None, self.num_capsule, self.dim_capsule) def MODEL(): input_image = Input(shape=(32, 32, 3)) x = Conv2D(64, (3, 3), activation='relu')(input_image) x = Conv2D(64, (3, 3), activation='relu')(x) x = AveragePooling2D((2, 2))(x) x = Conv2D(128, (3, 3), activation='relu')(x) x = Conv2D(128, (3, 3), activation='relu')(x) """ 现在我们将它转换为(batch_size, input_num_capsule, input_dim_capsule),然后连接一个胶囊神经层。模型的最后输出是10个维度为16的胶囊网络的长度 """ x = Reshape((-1, 128))(x) # (None, 100, 128) 相当于前一层胶囊(None, input_num, input_dim) capsule = Capsule(num_capsule=10, dim_capsule=16, routings=3, share_weights=True)(x) # capsule-(None,10, 16) output = Lambda(lambda z: K.sqrt(K.sum(K.square(z), axis=2)))(capsule) # 最后输出变成了10个概率值 model = Model(inputs=input_image, output=output) return model if __name__ == '__main__': # 加载数据 (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes) y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes) # 加载模型 model = MODEL() model.compile(loss=margin_loss, optimizer='adam', metrics=['accuracy']) model.summary() tfck = TensorBoard(log_dir='capsule') # 训练 data_augmentation = True if not data_augmentation: print('Not using data augmentation.') model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test), callbacks=[tfck], shuffle=True) else: print('Using real-time data augmentation.') # This will do preprocessing and realtime data augmentation: datagen = ImageDataGenerator( featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by dataset std samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=0, # randomly rotate images in 0 to 180 degrees width_shift_range=0.1, # randomly shift images horizontally height_shift_range=0.1, # randomly shift images vertically horizontal_flip=True, # randomly flip images vertical_flip=False) # randomly flip images # Compute quantities required for feature-wise normalization # (std, mean, and principal components if ZCA whitening is applied). datagen.fit(x_train) # Fit the model on the batches generated by datagen.flow(). model.fit_generator( datagen.flow(x_train, y_train, batch_size=batch_size), epochs=epochs, validation_data=(x_test, y_test), callbacks=[tfck], workers=4) ``` 以上为代码 运行后出现该问题 ![图片说明](https://img-ask.csdn.net/upload/201902/26/1551184741_476774.png) ![图片说明](https://img-ask.csdn.net/upload/201902/26/1551184734_845838.png) 用官方的胶囊网络keras实现更改为tf下的keras实现仍出现该错误。

keras下self-attention和Recall, F1-socre值实现问题?

麻烦大神帮忙看一下: (1)为何返回不了Precise, Recall, F1-socre值? (2)为何在CNN前加了self-attention层,训练后的acc反而降低在0.78上下? 【研一小白求详解,万分感谢大神】 ``` import os #导入os模块,用于确认文件是否存在 import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.callbacks import Callback from sklearn.metrics import f1_score, precision_score, recall_score maxlen = 380#句子长截断为100 training_samples = 20000#在 200 个样本上训练 validation_samples = 5000#在 10 000 个样本上验证 max_words = 10000#只考虑数据集中前 10 000 个最常见的单词 def dataProcess(): imdb_dir = 'data/aclImdb'#基本路径,经常要打开这个 #处理训练集 train_dir = os.path.join(imdb_dir, 'train')#添加子路径 train_labels = [] train_texts = [] for label_type in ['neg', 'pos']: dir_name = os.path.join(train_dir, label_type) for fname in os.listdir(dir_name):#获取目录下所有文件名字 if fname[-4:] == '.txt': f = open(os.path.join(dir_name, fname),'r',encoding='utf8') train_texts.append(f.read()) f.close() if label_type == 'neg': train_labels.append(0) else:train_labels.append(1) #处理测试集 test_dir = os.path.join(imdb_dir, 'test') test_labels = [] test_texts = [] for label_type in ['neg', 'pos']: dir_name = os.path.join(test_dir, label_type) for fname in sorted(os.listdir(dir_name)): if fname[-4:] == '.txt': f = open(os.path.join(dir_name, fname),'r',encoding='utf8') test_texts.append(f.read()) f.close() if label_type == 'neg': test_labels.append(0) else: test_labels.append(1) #对数据进行分词和划分训练集和数据集 tokenizer = Tokenizer(num_words=max_words) tokenizer.fit_on_texts(train_texts)#构建单词索引结构 sequences = tokenizer.texts_to_sequences(train_texts)#整数索引的向量化模型 word_index = tokenizer.word_index#索引字典 print('Found %s unique tokens.' % len(word_index)) data = pad_sequences(sequences, maxlen=maxlen) train_labels = np.asarray(train_labels)#把列表转化为数组 print('Shape of data tensor:', data.shape) print('Shape of label tensor:', train_labels.shape) indices = np.arange(data.shape[0])#评论顺序0,1,2,3 np.random.shuffle(indices)#把评论顺序打乱3,1,2,0 data = data[indices] train_labels = train_labels[indices] x_train = data[:training_samples] y_train = train_labels[:training_samples] x_val = data[training_samples: training_samples + validation_samples] y_val = train_labels[training_samples: training_samples + validation_samples] #同样需要将测试集向量化 test_sequences = tokenizer.texts_to_sequences(test_texts) x_test = pad_sequences(test_sequences, maxlen=maxlen) y_test = np.asarray(test_labels) return x_train,y_train,x_val,y_val,x_test,y_test,word_index embedding_dim = 100#特征数设为100 #"""将预训练的glove词嵌入文件,构建成可以加载到embedding层中的嵌入矩阵""" def load_glove(word_index):#导入glove的词向量 embedding_file='data/glove.6B' embeddings_index={}#定义字典 f = open(os.path.join(embedding_file, 'glove.6B.100d.txt'),'r',encoding='utf8') for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() # """转化为矩阵:构建可以加载到embedding层中的嵌入矩阵,形为(max_words(单词数), embedding_dim(向量维数)) """ embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in word_index.items():#字典里面的单词和索引 if i >= max_words:continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix if __name__ == '__main__': x_train, y_train, x_val, y_val,x_test,y_test, word_index = dataProcess() embedding_matrix=load_glove(word_index) #可以把得到的嵌入矩阵保存起来,方便后面fine-tune""" # #保存 from keras.models import Sequential from keras.layers.core import Dense,Dropout,Activation,Flatten from keras.layers.recurrent import LSTM from keras.layers import Embedding from keras.layers import Bidirectional from keras.layers import Conv1D, MaxPooling1D import keras from keras_self_attention import SeqSelfAttention model = Sequential() model.add(Embedding(max_words, embedding_dim, input_length=maxlen)) model.add(SeqSelfAttention(attention_activation='sigmod')) model.add(Conv1D(filters = 64, kernel_size = 5, padding = 'same', activation = 'relu')) model.add(MaxPooling1D(pool_size = 4)) model.add(Dropout(0.25)) model.add(Bidirectional(LSTM(64,activation='tanh',dropout=0.2,recurrent_dropout=0.2))) model.add(Dense(256, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(1, activation='sigmoid')) model.summary() model.layers[0].set_weights([embedding_matrix]) model.layers[0].trainable = False model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) class Metrics(Callback): def on_train_begin(self, logs={}): self.val_f1s = [] self.val_recalls = [] self.val_precisions = [] def on_epoch_end(self, epoch, logs={}): val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round() val_targ = self.validation_data[1] _val_f1 = f1_score(val_targ, val_predict) _val_recall = recall_score(val_targ, val_predict) _val_precision = precision_score(val_targ, val_predict) self.val_f1s.append(_val_f1) self.val_recalls.append(_val_recall) self.val_precisions.append(_val_precision) return metrics = Metrics() history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val), callbacks=[metrics]) model.save_weights('pre_trained_glove_model.h5')#保存结果 ```

使用keras画出模型准确率评估的执行结果时出现:

建立好深度学习的模型后,使用反向传播法进行训练。 定义了训练方式: ``` model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) ``` 执行训练: ``` train_history =model.fit(x=x_Train_normalize, y=y_Train_OneHot,validation_split=0.2, epochs=10,batch_size=200,verbose=2) ``` 执行后出现: ![图片说明](https://img-ask.csdn.net/upload/201910/17/1571243584_952792.png) 建立show_train_history显示训练过程: ``` import matplotlib.pyplot as plt def show_train_history(train_history,train,validation): plt.plot(train_history.history[train]) plt.plot(train_history.history[validation]) plt.title('Train History') plt.ylabel(train) plt.xlabel('Epoch') plt.legend(['train','validation'],loc='upper left') plt.show() ``` 画出准确率执行结果: ``` show_train_history(train_history,'acc','val_acc') ``` 结果出现以下问题: ![图片说明](https://img-ask.csdn.net/upload/201910/17/1571243832_179270.png) 这是怎么回事呀? 求求大佬救救孩子555

为什么我在predict_classes(x)中的x用了很多格式但总是报错?

#BP人工神经网络的实现 #1、读取数据 #2、keras.models Sequential /keras.layers.core Dense Activation #3、Sequential建立模型 #4、Dense建立层 #5、Activation激活函数 #6、compile模型编译 #7、fit训练(学习) #8、验证(测试,分类预测) #使用人工神经网络预测课程销量 #数据的读取与整理 import pandas as pda import numpy as npy fname = 'D:\\shuju\\fenleisuanfa\\lesson2.csv' dataf = pda.read_csv(fname) x = dataf.iloc[:,1:5].values y = dataf.iloc[:,5:6].values for i in range(0,len(x)): for j in range(0,len(x[i])): thisdata = x[i][j] if(thisdata =='是' or thisdata == '多' or thisdata == '高'): x[i][j] = 1 else: x[i][j] = 0 for i in range(0,len(y)): thisdata = y[i] if(thisdata == '高'): y[i] = 1 else: y[i] = 0 xf = pda.DataFrame(x) yf = pda.DataFrame(y) x2 = xf.values.astype(int) y2 = yf.values.astype(int) #使用人工神经网络模型 from keras.models import Sequential from keras.layers.core import Dense,Activation import keras.preprocessing.text as t from keras.preprocessing.text import Tokenizer as tk from keras.preprocessing.text import text_to_word_sequence model = Sequential() #输入层 model.add(Dense(10,input_dim = len(x2[0]))) model.add(Activation('relu')) #输出层 model.add(Dense(1,input_dim = 1)) model.add(Activation('sigmoid')) #模型的编译 model.compile(loss = 'binary_crossentropy',optimizer = 'adam', metrics = ['accuracy']) #训练 rst = model.fit(x2,y2,epochs = 10,batch_size = 100) #预测分类 model.predict_classes(x).reshape(len(x)) ![图片说明](https://img-ask.csdn.net/upload/201909/11/1568184347_152341.jpg) ![图片说明](https://img-ask.csdn.net/upload/201909/11/1568184147_136600.jpg) ![图片说明](https://img-ask.csdn.net/upload/201909/11/1568184174_122879.jpg)

求问怎么加dropout啊,急急急,在线等

#!/usr/bin/env python # encoding: utf-8 import matplotlib.pylab as plt from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.layers import Dropout import numpy as np from sklearn import datasets from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from keras.models import Sequential import sys import tensorflow as tf sys.path.append("../process")#添加其他文件夹 import data_input#导入其他模块 from traffic_network import LeNet import numpy as np from keras.models import Sequential from keras.layers import Dropout from keras.layers import Dense from keras.constraints import max_norm from keras.optimizers import SGD sgd = SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False) def train(aug, model,train_x,train_y,test_x,test_y): model.add(Dropout(rate=0.0, input_shape=(4,))) model.compile(loss="categorical_crossentropy", optimizer="sgd",metrics=["accuracy"])#配置 #model.fit(train_x,train_y,batch_size,epochs,validation_data=(test_x,test_y)) _history = model.fit_generator(aug.flow(train_x,train_y,batch_size=batch_size), validation_data=(test_x,test_y),steps_per_epoch=len(train_x)//batch_size, epochs=epochs,verbose=1) #拟合,具体fit_generator请查阅其他文档,steps_per_epoch是每次迭代,需要迭代多少个batch_size,validation_data为test数据,直接做验证,不参与训练 model.save("../predict/traffic_model.h5") print(_history.history.keys()) plt.style.use("ggplot")#matplotlib的美化样式 plt.figure() N = epochs plt.plot(np.arange(0,N),_history.history["loss"],label ="train_loss")#model的history有四个属性,loss,val_loss,acc,val_acc plt.plot(np.arange(0,N),_history.history["val_loss"],label="val_loss") plt.plot(np.arange(0,N),_history.history["acc"],label="train_acc") plt.plot(np.arange(0,N),_history.history["val_acc"],label="val_acc") plt.title("loss and accuracy") plt.xlabel("epoch") plt.ylabel("loss/acc") plt.legend(loc="best") plt.savefig("../result/result.png") plt.show() if __name__ =="__main__": channel = 3 height = 32 width = 32 class_num = 8 norm_size = 32#参数 batch_size = 64 epochs = 1000#40 DROPOUT = 0.3 model = LeNet.neural(channel=channel, height=height, width=width, classes=class_num)#网络 train_x, train_y = data_input.load_data("../data/train", norm_size, class_num) test_x, test_y = data_input.load_data("../data/test", norm_size, class_num)#生成数据 aug = ImageDataGenerator(rotation_range=30,width_shift_range=0.1, height_shift_range=0.1,shear_range=0.2,zoom_range=0.2, horizontal_flip=True,fill_mode="nearest")#数据增强,生成迭代器 train(aug,model,train_x,train_y,test_x,test_y)#训练 我这里怎么加dropout啊,rate太高val_acc就会变成恒定是1.0然后train_acc识别率也也上不去了,求大神指导啊

Keras, Tensorflow, ValueError

把csdn上一个颜值打分程序放到jupyter notebook上跑,程序如下: ``` from keras.applications import ResNet50 from keras import optimizers from keras.layers import Dense, Dropout from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint from keras.backend.tensorflow_backend import set_session os.environ['CUDA_VISIBLE_DEVICES'] = '1' config = tf.ConfigProto() config.gpu_options.allow_growth = True set_session(tf.Session(config=config)) batch_size = 32 target_size = (224, 224) resnet = ResNet50(include_top=False, pooling='avg') resnet.trainable = False # keras.backend.clear_session() # tf.reset_default_graph() model = Sequential() model.add(resnet) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) print(model.summary()) model.compile(optimizer=optimizers.SGD(lr=0.001), loss='mse') callbacks = [EarlyStopping(monitor='val_loss', patience=5, verbose=1, min_delta=1e-4), ReduceLROnPlateau(monitor='val_loss', patience=3, factor=0.1, epsilon=1e-4), ModelCheckpoint(monitor='val_loss', filepath='weights/resnet50_weights.hdf5', save_best_only=True, save_weights_only=True)] train_file_list, test_file_list = read_data_list() train_steps_per_epoch = math.ceil(len(train_file_list) / batch_size) test_steps_per_epoch = math.ceil(len(test_file_list) / batch_size) train_data = DataGenerator(train_file_list, target_size,batch_size) test_data = DataGenerator(test_file_list, target_size, batch_size) model.fit_generator(train_data, steps_per_epoch=train_steps_per_epoch, epochs=30, verbose=1, callbacks=callbacks, validation_data=test_data, validation_steps=test_steps_per_epoch, use_multiprocessing=True) ``` 结果引发如下错误: ValueError Traceback (most recent call last) <ipython-input-34-ae0a8870fdc1> in <module>() 20 # tf.reset_default_graph() 21 model = Sequential() ---> 22 model.add(resnet) 23 model.add(Dropout(0.5)) 24 model.add(Dense(1, activation='sigmoid')) ...Ignoring many tracing lines... ValueError: Variable bn_conv1/moving_mean/biased already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at: File "xxxx\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1269, in __init__ self._traceback = _extract_stack() File "xxxx\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2506, in create_op original_op=self._default_original_op, op_def=op_def) File "xxxx\anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op op_def=op_def) 我按照网上说法在model语句前加了tf.reset_default_graph() ,结果又产生新的error: ValueError: Tensor("conv1_1/kernel:0", shape=(7, 7, 3, 64), dtype=float32_ref) must be from the same graph as Tensor("resnet50/conv1_pad/Pad:0", shape=(?, ?, ?, 3), dtype=float32). 又按照网上说法加了keras.backend.clear_session(),总共加的两句前前后后在很多地方放了测试,结果都会有新的问题: ValueError: Tensor("conv1/kernel:0", shape=(7, 7, 3, 64), dtype=float32_ref) must be from the same graph as Tensor("resnet50/conv1_pad/Pad:0", shape=(?, ?, ?, 3), dtype=float32). 请教大牛究竟该如何彻底解决问题。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

获取Linux下Ftp目录树并逐步绑定到treeview

在linux下抓取目录树,双击后获取该节点子节点(逐步生成)。另外有两个类,一个是windows下的(一次性获取目录树),一个是linux下的(足部获取目录树)

NS网络模拟和协议仿真源代码

NS网络模拟和协议仿真源代码,包含代码说明及协议分析

简单的NS3网络模拟仿真(计算机网络作业)

简单的NS3网络模拟仿真,内附有PPT演示。论文评述。以及简单的安装教程。

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

cuda开发cutilDLL

包括cutil32.dll、cutil32D.dll、cutil32.lib、cutil32D.lib,以及附带的glew32.lib/freeglut.lib

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

Tensorflow与python3.7适配版本

tensorflow与python3.7匹配的最新库,更新了python3.7以后可以自行下载,或者去国外python的扩展包下载界面自行下载。

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

专为程序员设计的数学课

<p> 限时福利限时福利,<span>15000+程序员的选择!</span> </p> <p> 购课后添加学习助手(微信号:csdn590),按提示消息领取编程大礼包!并获取讲师答疑服务! </p> <p> <br> </p> <p> 套餐中一共包含5门程序员必学的数学课程(共47讲) </p> <p> 课程1:《零基础入门微积分》 </p> <p> 课程2:《数理统计与概率论》 </p> <p> 课程3:《代码学习线性代数》 </p> <p> 课程4:《数据处理的最优化》 </p> <p> 课程5:《马尔可夫随机过程》 </p> <p> <br> </p> <p> 哪些人适合学习这门课程? </p> <p> 1)大学生,平时只学习了数学理论,并未接触如何应用数学解决编程问题; </p> <p> 2)对算法、数据结构掌握程度薄弱的人,数学可以让你更好的理解算法、数据结构原理及应用; </p> <p> 3)看不懂大牛代码设计思想的人,因为所有的程序设计底层逻辑都是数学; </p> <p> 4)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; </p> <p> 5)想修炼更好的编程内功,在遇到问题时可以灵活的应用数学思维解决问题。 </p> <p> <br> </p> <p> 在这门「专为程序员设计的数学课」系列课中,我们保证你能收获到这些:<br> <br> <span> </span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">①价值300元编程课程大礼包</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">②应用数学优化代码的实操方法</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">③数学理论在编程实战中的应用</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">④程序员必学的5大数学知识</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">⑤人工智能领域必修数学课</span> </p> <p> <br> 备注:此课程只讲程序员所需要的数学,即使你数学基础薄弱,也能听懂,只需要初中的数学知识就足矣。<br> <br> 如何听课? </p> <p> 1、登录CSDN学院 APP 在我的课程中进行学习; </p> <p> 2、登录CSDN学院官网。 </p> <p> <br> </p> <p> 购课后如何领取免费赠送的编程大礼包和加入答疑群? </p> <p> 购课后,添加助教微信:<span> csdn590</span>,按提示领取编程大礼包,或观看付费视频的第一节内容扫码进群答疑交流! </p> <p> <img src="https://img-bss.csdn.net/201912251155398753.jpg" alt=""> </p>

实现简单的文件系统

实验内容: 通过对具体的文件存储空间的管理、文件的物理结构、目录结构和文件操作的实现,加深对文件系统内部功能和实现过程的理解。 要求: 1.在内存中开辟一个虚拟磁盘空间作为文件存储器,在其上实现一个简

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

四分之一悬架模型simulink.7z

首先建立了四分之一车辆悬架系统的数学模型,应用MATLAB/Simulink软件建立该系统的仿真模型,并输入路面激励为随机激励,控制不同的悬架刚度和阻尼,选用最优的参数得到车辆悬架的振动加速度变化曲线

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

Java8零基础入门视频教程

这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

C/C++学习指南全套教程

C/C++学习的全套教程,从基本语法,基本原理,到界面开发、网络开发、Linux开发、安全算法,应用尽用。由毕业于清华大学的业内人士执课,为C/C++编程爱好者的教程。

pokemmo的资源

pokemmo必须的4个rom 分别为绿宝石 火红 心金 黑白 还有汉化补丁 资源不错哦 记得下载

test_head.py

本文件主要是针对使用dlib的imglab标注工具标记的目标检测框和关键点检测而生成的xml文件, 转换为coco数据集格式.

Java面试史上最全的JAVA专业术语面试100问 (前1-50)

前言: 说在前面, 面试题是根据一些朋友去面试提供的,再就是从网上整理了一些。 先更新50道,下一波吧后面的也更出来。 求赞求关注!! 废话也不多说,现在就来看看有哪些面试题 1、面向对象的特点有哪些? 抽象、继承、封装、多态。 2、接口和抽象类有什么联系和区别? 3、重载和重写有什么区别? 4、java有哪些基本数据类型? 5、数组有没有length()方法?String有没有length()方法? 数组没有length()方法,它有length属性。 String有length()方法。 集合求长度用

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

linux“开发工具三剑客”速成攻略

工欲善其事,必先利其器。Vim+Git+Makefile是Linux环境下嵌入式开发常用的工具。本专题主要面向初次接触Linux的新手,熟练掌握工作中常用的工具,在以后的学习和工作中提高效率。

DirectX修复工具V4.0增强版

DirectX修复工具(DirectX Repair)是一款系统级工具软件,简便易用。本程序为绿色版,无需安装,可直接运行。 本程序的主要功能是检测当前系统的DirectX状态,如果发现异常则进行修复

20行代码教你用python给证件照换底色

20行代码教你用python给证件照换底色

2019 Python开发者日-培训

本次活动将秉承“只讲技术,拒绝空谈”的理念,邀请十余位身处一线的Python技术专家,重点围绕Web开发、自动化运维、数据分析、人工智能等技术模块,分享真实生产环境中使用Python应对IT挑战的真知灼见。此外,针对不同层次的开发者,大会还安排了深度培训实操环节,为开发者们带来更多深度实战的机会。

我以为我对Mysql事务很熟,直到我遇到了阿里面试官

太惨了,面试又被吊打

相关热词 c#设计思想 c#正则表达式 转换 c#form复制 c#写web c# 柱形图 c# wcf 服务库 c#应用程序管理器 c#数组如何赋值给数组 c#序列化应用目的博客园 c# 设置当前标注样式
立即提问