编程python 小问题备忘

1.生成小数

A = np.arange(0,5,0.01)
A
Out[5]: 
array([0.  , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 ,
       0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 , 0.21,
       0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3 , 0.31, 0.32,
       0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4 , 0.41, 0.42, 0.43,
       0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5 , 0.51, 0.52, 0.53, 0.54,
       0.55, 0.56, 0.57, 0.58, 0.59, 0.6 , 0.61, 0.62, 0.63, 0.64, 0.65,
       0.66, 0.67, 0.68, 0.69, 0.7 , 0.71, 0.72, 0.73, 0.74, 0.75, 0.76,
       0.77, 0.78, 0.79, 0.8 , 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87,
       0.88, 0.89, 0.9 , 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98,
       0.99, 1.  , 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09,
       1.1 , 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2 ,
       1.21, 1.22, 1.23, 1.24, 1.25, 1.26, 1.27, 1.28, 1.29, 1.3 , 1.31,
       1.32, 1.33, 1.34, 1.35, 1.36, 1.37, 1.38, 1.39, 1.4 , 1.41, 1.42,
       1.43, 1.44, 1.45, 1.46, 1.47, 1.48, 1.49, 1.5 , 1.51, 1.52, 1.53,

2.PCA与SVD 当矩阵对称时,可证明,两种方法的特征向量相同

u,sigma,vt = np.linalg.svd(np.dot(X.T,X))

V = vt.T

V
Out[106]: 
array([[-0.60480295,  0.51573258, -0.24030538,  0.40956589, -0.37781265],
       [-0.45461252, -0.42466685,  0.67842382, -0.08945472, -0.38042673],
       [-0.3539136 ,  0.24283785, -0.17407516, -0.88488594,  0.04949405],
       [-0.32673754,  0.25846818,  0.4100625 ,  0.16537152,  0.79431592],
       [-0.44218615, -0.65414215, -0.53248571,  0.11782517,  0.28132838]])

u,sigma,vt = np.linalg.svd(X)

VV = vt.T

VV
Out[109]: 
array([[-0.60480295, -0.51573258,  0.24030538, -0.40956589,  0.37781265],
       [-0.45461252,  0.42466685, -0.67842382,  0.08945472,  0.38042673],
       [-0.3539136 , -0.24283785,  0.17407516,  0.88488594, -0.04949405],
       [-0.32673754, -0.25846818, -0.4100625 , -0.16537152, -0.79431592],
       [-0.44218615,  0.65414215,  0.53248571, -0.11782517, -0.28132838]])

sigma
Out[110]: array([3.28509584, 1.20818383, 1.07187278, 0.76833701, 0.53152317])
    data1 = DataGeneration.data_generation(X_train, index=21)
    data2 = DataGeneration.data_generation(X_train, index=21)
    data3 = DataGeneration.data_generation(X_train, index=21)
    sum1 = 0
    sum1 += np.dot((data2 - data1).T, (data2 - data1)) + np.dot((data3 - data1).T, (data3 - data1)) \
            + np.dot((data3 - data2).T, (data3 - data2))
    for lamb in np.arange(0, 1, 1):
        S_new = X_train.T.dot(X_train) - lamb * sum1  # 对称的,可以用SVD
        # print(S_new)
        # eigvalues, eigvectors = np.linalg.eigh(S_new)  # 进行特征值分解
        # index = np.argsort(eigvalues)[::-1]
        # eigvalues = eigvalues[index]
        # eigvectors = eigvectors[index]
        # P = eigvectors
        # Lambda = eigvalues
        u, sigma, vt = np.linalg.svd(S_new)      # 对X进行SVD分解
        P = vt.T
        Lambda = np.square(sigma)

3. https://blog.csdn.net/helunqu2017/article/details/78629136

matplotlib命令与格式:设置折线与点属性

ms:点的大小,lw:线的大小,alpha:透明度。subplot(1,2,1)

def Drwa_lamb(X, SPE_lamb, T2_lamb):
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.plot(X, SPE_lamb[0, :], '.-r', linewidth=1, label='FAR')
    plt.plot(X, SPE_lamb[1, :], '.-b', linewidth=1, label='FDR')
    plt.title('SPE')
    plt.legend(loc='upper right')
    plt.xlabel('lamb')

    plt.subplot(1, 2, 2)
    plt.plot(X, T2_lamb[0, :], '.-r', ms=1, linewidth=1, alpha=0.3, label='FAR')
    plt.plot(X, T2_lamb[1, :], '.-b', ms=0.5, linewidth=1, alpha=1, label='FDR')
    plt.title('$T^2$')
    plt.legend(loc='upper right')
    plt.xlabel('lamb')
    plt.show()

3. 图像读取原文: https://blog.csdn.net/hjxu2016/article/details/79104607 

#方法二:利用matplotlib.pyplot as plt用于显示图片
# matplotlib.image as mpimg 用于读取图片
# 并且读取出来就是array格式
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
I = mpimg.imread('./cc_1.png')
print I.shape
plt.imshow(I)

4.python 改图形布局

import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(6, 6.5))
for i in range(4):
    ax = plt.subplot(221+i)
    alpha = 0.98 / 4 * i + 0.01
    ax.set_title('%.3f' % alpha)
    t1 = np.arange(0.0, 1.0, 0.01)
    for n in [1, 2, 3, 4]:
        plt.plot(t1, t1 ** n, label="n=%d" % n)
    leg = plt.legend(loc='best', ncol=4, mode="expand", shadow=True)
    leg.get_frame().set_alpha(alpha)

plt.savefig('1.png')
plt.show()
--------------------- 
作者:肥宅_Sean 
来源:CSDN 
原文:https://blog.csdn.net/a19990412/article/details/81407640 
版权声明:本文为博主原创文章,转载请附上博文链接!

5. array 与 list 相互转换

#将list转化为 numpy.ndarray

array=numpy.array(list) 

将numpy.ndarray转化为list

array=numpy.array([1,2,3,4,5,6])
#输出numpy.ndarray类型
print type(array)
print array
list=array.tolist()

6. numpy保存成csv

import numpy
my_matrix = numpy.loadtxt(open("D:\\test.csv","rb"), delimiter=",", skiprows=0)

import numpy
numpy.savetxt("new.csv", my_matrix, delimiter=',')

7.pycharm 画图显示不出

很可能是将画图界面浮动,导致缩小。解决:先将pycharm最小化,看桌面的边边角角有没有画的图的小样子

8. python 定制坐标轴

https://blog.csdn.net/wuzlun/article/details/80053277

https://blog.csdn.net/helunqu2017/article/details/78736415     这个有用

x_ticks = np.arange(1, 22, 1)  # 设置x轴刻度显示
plt.xticks(x_ticks)

#设置刻度标签字体属性
plt.xticks(fontsize=16, color="red", rotation=45)
# 显示x轴的刻标以及对应的标签
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )

#设置坐标轴范围
plt.xlim((-5, 5))     #也可写成plt.xlim(-5, 5) 
plt.ylim((-2, 2))     #也可写成plt.ylim(-2, 2)
#设置坐标轴名称
 
plt.xlabel("Data sets",fontsize=13,fontweight='bold')
plt.ylabel("Accuracy",fontsize=13,fontweight='bold')
#设置坐标轴刻度
my_x_ticks = np.arange(-5, 5, 0.5)
my_y_ticks = np.arange(-2, 2, 0.3)
plt.xticks(my_x_ticks)
plt.yticks(my_y_ticks)
#显示出所有设置
plt.show()


import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rc('font', family='Times New Roman')   # 将全局字体改为Times New Roman

# 图例位置
plt.legend(loc='upper right')

# 空心圆
plt.plot(range(1, 22, 1), X[i * 21:(i + 1) * 21, 5].T, '-.o', markerfacecolor='none', label='ACPCA')


# 将图片保存到文件夹
# '在本文件下创建保存路径'
localtime = time.strftime("%Y-%m-%d-%H-%M-%S")
save_path = os.getcwd() + '\\' + localtime
os.makedirs(save_path)

plt.savefig(save_path + '\\' + 'index=' + str(i) + '_lambda' + str(X[i * 21, 14]) + '.png')
plt.show()

9. 产生随机不相同的整数

利用Python中的randomw.sample()函数实现  
resultList=random.sample(range(A,B),N); #表示从[A,B]间随机生成N个数,结果以列表返回

10. 隔行取数组

想要隔行取:f[2::2,2::2]   开始::间隔几个

猜你喜欢

转载自blog.csdn.net/qq_26004387/article/details/88287376