Open NarcissusInMirror opened 5 years ago
w
举例),选择的方法是w - 学习率*(lossfunc对w的偏导数)
![](http://latex.codecogs.com/gif.latex?\w=w-\eta*\frac{\partial f(x)}{\partial w}),这里有如下直观的理解:当lossfunc
对w
的偏导数为正,说明增加w
会使得lossfunc
增大,故用w
减去学习率乘以偏导数,减小w
以减小lossfunc
,反之亦然。keras.layers.concatenate
main_input = Input(shape=(100, 100, 3))
auxiliary_input = Input(shape=(100, 100, 1))
input_tensor = concatenate([main_input, auxiliary_input])
如果是自己搭网络,继续搭即可,如果是应用keras的现有网络,需注意如下步骤,这里以VGG16为例:
'''
input_tensor要用列表记录全部输入
weights=None代表不使用预训练的权重,这里是因为训练权重输入是3通道图像,而因为进行了拼接
输入通道数会大于三,所以权重无法使用,会报错
include_top是选择是否包含最后的几个全连接层,选择false以适应自己的分类数目
'''
base_model = VGG16(input_tensor=[main_input, auxiliary_input], weights=None, include_top=False)
x = base_model.output
flatten_1 = Flatten()(x) dense_1 = Dense(512)(flatten_1) activation_1 = Activation('relu')(dense_1) drop_2 = Dropout(0.5)(activation_1) dense_2 = Dense(4)(drop_2) activation_2 = Activation('sigmoid')(dense_2)
model = Model(inputs=base_model.input, outputs=activation_2)
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
model.fit([x_train, x_aux], y_train, batch_size=32, nb_epoch=50,callbacks=[TensorBoard(log_dir='./log_dir', write_graph=True)],validation_data=([x_test, x_aux_test], y_test))
Traditional cameras capture images: synchronous intensity measurements; but events are asynchronous reports of local intensity difference, and there is no global or persistent measurement of intensity which would permit normal approaches to correspondence to be used (feature extraction, patch alignment)
Optical flow is normally understood as the correspondence field between two temporally close intensity images — an estimation of two parameters per pixel, the horizontal and vertical displacement between one frame and the next.
keras中的正则项要在每个layer上添加?不是很懂。
batch-GD, SGD, Mini-batch-GD, Stochastic GD, Online-GD -- 大数据背景下的梯度训练算法
name | sample size | batch size | 定义 |
---|---|---|---|
batch GD | N | N | 每次迭代的梯度方向计算由所有训练样本共同投票决定 |
mini-batch GD | N | m | 每次迭代的梯度方向计算由所有m个训练样本共同投票决定 |
SGD | N | 1 | mini-batch GD的一个特殊应用,每个batch只有一个样本 |
os.listdir(PATHNAME)
输出文件名,并对比两个列表,看看两个列表是从哪一个元素开始不同的,从而找到标注错误的图片。但是实际操作后发现两种方法读取出来的列表顺序并不相同,os.listdir(PATHNAME)
的读取更像是随机的,而csv中由于按行读取,所以读出来的文件名是从0.png
到'*.png的。即便是使用
sorted()函数对列表进行排序,得到的结果仍不是从0到n升序排列的,而是
0.png, 1.png, 11.png, 111.png`以此类推。这时便想到了python的集合数据结构。
应用以下几行代码即可轻松实现上面的需求。
image_lists = set() # 定义一个集合,初始化集合时必须用set(),而不能用{}
with open(CSV_FILE, 'r') as f: # 读取label,使用add()方法添加到集合中
reader = csv.reader(f)
for row in reader:
image_lists.add(row[0] + '.png')
label_lists = os.listdir(IMAGE_DIR) label_set = set() for i in label_lists: label_set.add(i) print(image_lists^label_set) # ^运算符,得到不同时包含于两个集合中的元素
__init__.py
文件即可。例如子目录名称为sub_dir
,目录下有模块test.py
,程序中输入语句import sub_dir.test
即可.
代表的是主文件所在目录,而非子目录路径。例如test.py
中要读取sub_dir
目录下的my_data.h5
文件,需在代码中写出完整路径f = h5py.File("./sub_dir/mydata.h5")
,若写f =h5py.File("./mydata.h5")
则访问的是执行文件所在目录,这一句并不会报错,而会在主目录下生成一个空的mydata.h5
文件,后续访问数据则会报错。
raise ExceptionName
即可以强制报错。try:
expected_size_of_next_frame = available_size / (self.buffer_size - (self.buffer_counter % 10) - 1)
except ZeroDivisionError:
expected_size_of_next_frame = self.first_frame_limit
import datetime
current_time = datetime.datetime.now() year = str(current_time.year) month = str(current_time.month) day = str(current_time.day) hour = str(current_time.hour) minute = str(currenttime.minute) timestamp = year + '' + month + '' + day + '' + hour + '_' + minute os.makedirs('record_files/weight_files/' + timestamp)
* 修改了损失函数,在独立测试集上的准确率提升了3~6个百分点
[Keras中自定义复杂的loss函数](https://spaces.ac.cn/archives/4493)
def mycrossentropy(y_true, y_pred, e=0.1):
loss1 = K.binary_crossentropy(y_true, y_pred)
loss2 = K.binary_crossentropy(K.ones_like(y_pred)/nb_classes, y_pred)
return (1-e)*loss1 + e*loss2
model.compile(loss=mycrossentropy, optimizer=sgd, metrics=['accuracy'])
![image](https://user-images.githubusercontent.com/28808216/55390310-8acb0a00-5569-11e9-8095-3c4647f22272.png)
https://stackoverflow.com/questions/15584608/python-opencv2-cv2-cv-fourcc-not-working-with-videowriter https://blog.csdn.net/Lay_ZY/article/details/53884420 https://docs.opencv.org/2.4.9/modules/highgui/doc/reading_and_writing_images_and_video.html#cv2.imwrite https://blog.csdn.net/u010167269/article/details/53268686
https://www.jianshu.com/p/7eec907827ee http://ufldl.stanford.edu/wiki/index.php/Exercise:PCA_and_Whitening http://ufldl.stanford.edu/wiki/index.php/PCA
读图片
cv2.imread(filename[, flags]) → retval
,flag介绍如下:
显示图片
cv2.imshow(dialog_box_name, img)
第一个参数是对话框的名字,第二个参数是要显示的图片,此代码后需接cv2.waitKey()
,参数为图片打开的时间,单位为毫秒,如果参数为空则时间为无限长。退出方法是将光标放在图片窗口上按esc键。写图片
cv2.imwrite(filename, img[, params]) → retval
读视频
cap = cv2.VideoCapture('bbb.avi')
初始化VideoCapture类success, frame = cap.read()
VideoCapture类的read方法返回两个值,第一个值为True或False,表示视频是否结束或相机是否断开,第二个值为一帧图像,每次调用此方法返回新的一帧写视频
cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) → retval
,这里[]
里的参数为可选参数,→ retval
表示返回一个变量,return value
。cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) → <VideoWriter object>
中,则表示所有参数都是可选的,并返回一个VideoWriter对象。video_writer.open('ccc.avi', cv2.VideoWriter_fourcc('P', 'I', 'M', '1'), 30, (640, 360), 0)
,官方文档给出的CV_FOURCC('M','J','P','G')
是会报错的,参见连接stack overflow, csdn。同时,framesize参数的长和宽要进行对调,否则在后续写如视频的时候会因为size不符合要求而导致无法写入,而不会报错,最后得到一个空的视频文件现有需求如下:需要将数组分为三个部分并进行赋值,大于threhold值的变为255,小于-threhold值的变为128,中间的值变为0。numpy数组支持形如array[array > threhold] = 255
、array[array < threhold] = 128
的操作,但不支持array[-threhold < array < threhold] = 0
的操作,也不支持array[-threhold < array and array < threhold] = 0
,故需要用到mask,代码如下
mask_array = np.ma.array(minus_frame, mask=(minus_frame < threshold.threshold))
mask_array_2 = np.ma.array(minus_frame, mask= (minus_frame > - threshold.threshold))
mask = mask_array.mask & mask_array_2.mask
分析:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7])
>>> b = np.ma.array(a, mask=(a < 3))
>>> b
masked_array(data=[--, --, 3, 4, 5, 6, 7],
mask=[ True, True, False, False, False, False, False],
fill_value=999999)
由以上代码可以看出,maskarray由三部分组成,data,mask和fill_value,可以通过.
进行访问
__del__(self)
右键表格 → Table Properties → Row → Options → Allow row to break across pages
alias name='command name'
只在当前的终端中有效,再打开一个终端就不行了alias name='command name'
即可,需打开新终端方可生效alias
即可
The commands in TeX and Plain TeX are still quite basic and it isn't easy to do complicated things with them. To help with this, Leslie Lamport created LaTeX in the early 1980s to provide a higher level language to work in than TeX.
LuaTeX is an attempt to extend the original TeX program with a more sensible programming language
BibTeX is reference management software for formatting lists of references.
吐槽一下:MacTex真的超级良心啊啊啊啊!就凭一个What is installed就把我圈粉了好吗!把安装的位置讲得那么清楚!我太希望所有软件都能有这么一个文档了! 主要分为两个部分:TeXLive-2018(可以理解为主题的程序)和GUI-Applications(相当于IDE)
/usr/local/texlive/
下,如果安装了多个版本会看到文件夹下有以版本年号命名的多个文件夹,互不冲突,下载新的安装包即会安装新的版本,修改的是symbolic link,即指向这些文件的链接。这些链接文件在/Library/TeX
下。TeXLiveUtility → Configure → Change Default TeX Live Version
,选择相应的版本即可。/Applications/TeX
下a = 为真时的结果 if 判定条件 else 为假时的结果
>>> result = 1 if 5>3 else 0
>>> result
1
Darwin is an open-source Unix-like operating system first released by Apple Inc. in 2000. It is composed of code developed by Apple, as well as code derived from NeXTSTEP, BSD, Mach, and other free software projects.
使用numpy的函数对图像进行减去均值的操作 使用到了numpy的以下函数:
有如下数组:(为明显起见,将数组用空行分为三段,代表三张图片)
>>> a = np.array([[[[10, 11, 12], [13, 14, 15]],
[[16, 17, 18], [19, 20, 21]]],
[[[22, 23, 24], [25, 26, 27]],
[[28, 29, 30], [31, 32, 33]]],
[[[34, 35, 36], [37, 38, 39]],
[[40, 41, 42], [43, 44, 45]]]])
形状为(3, 2, 2, 3)
,其中四个维度分别为(图片数目,行, 列, 通道数)
因此这里我们模拟的是3张223的图片,第一张图片的三各通道分别为
[[10, 13],
[16, 19]]
[[11, 14],
[17, 20]]
[[12, 15],
[18, 21]]
其他两张图片类似。
均值函数的使用方法为np.mean(ndarray, axis)
,这里比较关键的是axis的值。数组的axis是如何规定的呢?从最外层到最内层依次是0~n。这里的最内层,指的是最小的括号,最小的括号所包含的素个数即为第n维的维度。以此类推,倒数第二小的括号所包含的元素个数即为第n-1维的维度。
以以上数组为例,最小的括号是[10, 11, 12]
,包含3个元素,所以最后四维的维度是3,对应的axis为3,倒数第二小的括号包含[10, 11, 12], [13, 14, 15]这两个元素,所以倒数第第三维的维度是2,对应的axis为2
同理,第二维的维度也是2,对应的axis为1,第一维的维度为3,对应的axis为0。
我们所要计算的的是一个三通道图像每一个通道图像像素的均值,因此这里的axis应该选择第二和第三维,对应axis=(1, 2)
>>>a_mean = np.mean(a, axis=(1,2))
[[14.5 15.5 16.5]
[26.5 27.5 28.5]
[38.5 39.5 40.5]]
经过均值计算后,我们得到了一个(3, 3)
的数组,这里第一维的3代表图片的数目,第二维的3代表通道个数,下面我们需要把均值减掉,很明显,直接进行相减是行不通的。需要把均值数组reshape成图片的大小。在此之前,要用的np.tile(ndarray, tuple)
函数
>>> a_mean_tile = np.tile(a_mean, (1, 4))
[[14.5 15.5 16.5 14.5 15.5 16.5 14.5 15.5 16.5 14.5 15.5 16.5]
[26.5 27.5 28.5 26.5 27.5 28.5 26.5 27.5 28.5 26.5 27.5 28.5]
[38.5 39.5 40.5 38.5 39.5 40.5 38.5 39.5 40.5 38.5 39.5 40.5]]
tile函数的逻辑如下,参数列表中的元组是对各个维度的重复次数,这里的4表示对最小括号里的内容重复4次,因为图片的大小为2*2=4
, 对于尺寸为mn的图片,这里参数改为mn即可;1表示对次小括号里的内容重复1次,若输入整数则默认对最小括号内的内容进行重复,其余维度保持不变。在本例中,原数组是二维的,如果输入的元组的维度大于2,就会增加数组的维度,例如:
>>> a_mean_tile = np.tile(a_mean, (1, 1, 4))
[[[14.5 15.5 16.5 14.5 15.5 16.5 14.5 15.5 16.5 14.5 15.5 16.5]
[26.5 27.5 28.5 26.5 27.5 28.5 26.5 27.5 28.5 26.5 27.5 28.5]
[38.5 39.5 40.5 38.5 39.5 40.5 38.5 39.5 40.5 38.5 39.5 40.5]]]
最后,进行reshape操作,图片数目的维度填入-1即可
>>> a_mean_tile_reshape = np.reshape(a_mean_tile, (-1, 2, 2, 3))
[[[[14.5 15.5 16.5]
[14.5 15.5 16.5]]
[[14.5 15.5 16.5]
[14.5 15.5 16.5]]]
[[[26.5 27.5 28.5]
[26.5 27.5 28.5]]
[[26.5 27.5 28.5]
[26.5 27.5 28.5]]]
[[[38.5 39.5 40.5]
[38.5 39.5 40.5]]
[[38.5 39.5 40.5]
[38.5 39.5 40.5]]]]
完整代码如下:
a = np.array([[[[10, 11, 12], [13, 14, 15]],
[[16, 17, 18], [19, 20, 21]],
[[22, 23, 24], [25, 26, 27]]],
[[[28, 29, 30], [31, 32, 33]],
[[34, 35, 36], [37, 38, 39]],
[[40, 41, 42], [43, 44, 45]]],
[[[46, 47, 48], [49, 50, 51]],
[[52, 53, 54], [55, 56, 57]],
[[58, 59, 60], [61, 62, 63]]]])
a_mean = np.reshape(np.tile(np.mean(a, axis=(1,2)), (1, 6)), (-1, 3, 2, 3))
b = a - a_mean_tile_reshape
如何理解主成分分析中的协方差矩阵的特征值的几何含义? Deep Learning Tutorial - PCA and Whitening
$ conda install scikit-learn
K-Fold官方文档 使用较为简单:
>>> from sklearn.model_selection import KFold
>>> kf = KFold(n_splits=5) # n_splits是数据分割的数目如果用20%的数据作为验证集,就设为5即可
>>> kf.get_n_splits()
5
>>> x = np.array(...)
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
>>> y = np.array([1, 2, 3, 4, 5])
>>> print(kf)
KFold(n_splits=5, random_state=None, shuffle=False) # 如果不shuffle数据的话后两个参数用不到
>>> for train_index, test_index in kf.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 2 3 4] TEST: [0]
TRAIN: [0 2 3 4] TEST: [1]
TRAIN: [0 1 3 4] TEST: [2]
TRAIN: [0 1 2 4] TEST: [3]
TRAIN: [0 1 2 3] TEST: [4]
# 这个函数实则生成的就是n_split组数组的index
linux下vim和bash配置文件 这篇文章里还有许多其他的配置值得研究。
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
https://en.wikipedia.org/wiki/Logit https://github.com/keras-team/keras/blob/master/keras/metrics.py https://stackoverflow.com/questions/42081257/keras-binary-crossentropy-vs-categorical-crossentropy-performance https://stackoverflow.com/questions/45741878/using-binary-crossentropy-loss-in-keras-tensorflow-backend
tf.nn.sigmoid binary cross entropy logit probability
2019.3.21工作日志
$ setsid python a.py > a.txt &
,其中setsid使得命令的父进程id为1,并将输出重定向至a.txt,&
则使命令在后台运行,同时会返回一个进程ID。值得注意的是,此条命令下返回的id用$ps -ef|grep
无法找到,需将ID+1才是真正的进程ID,原因未知.masked_array = np.ma.array(imageArray, mask=(imageArray==0))
这行代码为imageArray构建mask,mask的位置是数组内所有值为0的位置,这些位置被置位True,代表会被mask。这里的应用场景是计算图片内除了黑色部分的均值,代码如下mean_value = masked_array.mean()
imageArray[imageArray < mean_value] = 0
a = [1, 2, 3]
,又定义了b = a
,无论修改b还是a都会改变[1, 2, 3]