常用代码和实用小工具

一、利用python画混淆矩阵

import matplotlib.pyplot as plt
import numpy as np

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    # # Compute confusion matrix
    # cm = confusion_matrix(y_true, y_pred)
    # Only use the labels that appear in the data
    #classes = classes[unique_labels(y_true, y_pred)]
    # labels = [0,1,2,3,4,5,6]
    # classes = classes[labels]
    # classes = ['anger', 'contempt', 'disgust', 'fear', 'happy', 'sadness', 'surprise']
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    # print(im)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    # Rotate the tick labels and set their alignment.
    # plt.setp(ax.get_xticklabels(), rotation=90, ha="right",
    #          rotation_mode="anchor")
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.2f' if normalize else '.0f'
    # print(fmt)
    thresh = cm.max() / 2.
    # print(thresh)
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    return ax

#confusion matrix
cm = []
cm_row_0 = [120, 0, 4, 2, 0, 8, 1]
cm_row_1 = [15, 27, 0, 6, 1, 3, 2]
cm_row_2 = [2, 1, 171, 0, 3, 0, 0]
cm_row_3 = [0, 6, 0, 61, 3, 2, 3]
cm_row_4 = [1, 0, 0, 0, 206, 0, 0]
cm_row_5 = [17, 3, 0, 0, 0, 63, 1]
cm_row_6 = [3, 5, 0, 2, 0, 2, 237]
cm.append(cm_row_0)
cm.append(cm_row_1)
cm.append(cm_row_2)
cm.append(cm_row_3)
cm.append(cm_row_4)
cm.append(cm_row_5)
cm.append(cm_row_6)
# print(cm,cm.size())
cm = np.array(cm)
print(cm)
print(cm.shape)

class_names = ['anger', 'contempt', 'disgust', 'fear', 'happy', 'sadness', 'surprise']

np.set_printoptions(precision=2)

# Plot non-normalized confusion matrix
plot_confusion_matrix(cm, classes=class_names,
                      title='Confusion matrix')
#
# # Plot normalized confusion matrix
plot_confusion_matrix(cm, classes=class_names, normalize=True,
                      title='Normalized confusion matrix')

plt.show()

# #confusion matrix
# cm = []
# cm_row_0 = [42, 0, 1, 0, 0, 2, 0]
# cm_row_1 = [2, 15, 0, 0, 0, 1, 0]
# cm_row_2 = [4, 0, 55, 0, 0, 0, 0]
# cm_row_3 = [0, 0, 1, 23, 0, 1, 0]
# cm_row_4 = [0, 0, 0, 1, 68, 0, 0]
# cm_row_5 = [2, 0, 0, 1, 0, 25, 0]
# cm_row_6 = [0, 1, 0, 0, 0, 1, 81]
# cm.append(cm_row_0)
# cm.append(cm_row_1)
# cm.append(cm_row_2)
# cm.append(cm_row_3)
# cm.append(cm_row_4)
# cm.append(cm_row_5)
# cm.append(cm_row_6)
# # print(cm,cm.size())
# cm = np.array(cm)
# print(cm)
# print(cm.shape)

# class_names = ['anger', 'contempt', 'disgust', 'fear', 'happy', 'sadness', 'surprise', 'neutral']

# np.set_printoptions(precision=2)

# # Plot non-normalized confusion matrix
# plot_confusion_matrix(cm, classes=class_names,
#                       title='Confusion matrix')
# #
# # # Plot normalized confusion matrix
# plot_confusion_matrix(cm, classes=class_names, normalize=True,
#                       title='Normalized confusion matrix')

# plt.show()


二、利用conda创建python虚拟环境以及需求文件的创建及使用

1、ubuntu安装Anaconda 具体步骤1

2、创建虚拟环境具体步骤4

3、需求文件requirements.txt的创建及使用参考只想生成项目需要的依赖部分

三、Tmux 使用教程 具体步骤11

四、Sublime text3 连接sftp/ftp(远程服务器)

这个教程更完整?
具体步骤8

五、ubuntu下sh脚本的写法具体步骤7

六、一行python代码能干啥

1.print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
2.print(''.join(__import__('random').choice('\u2571\u2572') for i in range(50*24)))
3.print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0else' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))
4.print('\n'.join([''.join(['*' if abs((lambda a:lambda z,c,n:a(a,z,c,n))(lambda s,z,c,n:z if n==0 else s(s,z*z+c,c,n-1))(0,0.02*x+0.05j*y,40))<2 else ' ' for x in range(-80,20)]) for y in range(-20,20)]))

七、Linux下查看文件夹大小

du -h --max-depth=1 /home 仅列出home目录下面所有的一级目录文件大小

八、从服务器拷贝文件到本地/移动硬盘:Xftp

Xftp使用方法

九、可视化

    #创建文件夹
    def mkdir(self, path):  # 判断是否存在指定文件夹,不存在则创建 # TypeError: mkdir() takes 1 positional argument but 2 were given
        # 引入模块
        import os

        # # 去除首位空格
        # # print(path)
        # path = path.strip()
        # # print(path)
        # # 去除尾部 \ 符号
        # path = path.rstrip("\\")
        # # print(path)

        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists = os.path.exists(path)

        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path)
            return True
        else:

            return False
            print(conv1.shape) # torch.Size([111, 16, 32, 32])
            features = conv1
            for ith_feature in range(features.shape[1]):
                feature = features[0, ith_feature, :, :]
                print('for ith_feature:{}  feature.shape:{}'.format(ith_feature, feature.shape)) # for ith_feature:0  feature.shape:torch.Size([32, 32])
                feature = feature.data.cpu().numpy()
                # TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
                # use sigmod to [0,1]
                feature = 1.0 / (1 + np.exp(-1 * feature))
                # to [0,255]
                feature = np.round(feature * 255)
                self.mkdir('./feature/conv1')
                cv2.imwrite('./feature/conv1' + '/' + str(ith_feature) + '.jpg', feature)

十、手把手教你使用 Endnote 导入文献,五分钟包会

新建一个数据库,google 引用处点击EndNote,双击下载文件!
以下还未看!
Endnote 使用简易教程(科研狗必备)
EndNote x9下载、安装及使用详细教程
手把手教你使用EndNote X9》正式发布啦~

十一、将移动硬盘的数据拷贝到服务器

先将移动硬盘的数据zip【工具:Bandizip】(不超过5G比较好?因为未压缩时很容易传断),然后用Xftp传到服务器,linux解压命令参考如下:

unzip -d /home/woomay/1009-woomay/fer/test_txt /home/woomay/1009-woomay/fer/test_txt.zip

会在/home/woomay/1009-woomay/fer/目录下创建test_txt文件夹,并将/home/woomay/1009-woomay/fer/test_txt.zip解压在test_txt文件夹下。

十二、将移动硬盘挂载到服务器上(未验证)

from CC
sudo fdisk -l 这个命令看插上去的硬盘号

sudo mount /dev/sdb1 ./ 这个命令挂载到一个目录下,建议重建一个新目录,然后cp -r就好了。第二个命令的、dev/sdb1 是第一个命令查到的硬盘号 , ./换成想挂载的目录文件夹。

(有root权限的账号,见手机)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值