python经常忘记的笔记

安装库的几个方法

  1. 修改下载源
    pip install matplotlib -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
    https://www.cnblogs.com/lpl521/p/6778048.html
  2. 事先下载whl文件
    windows的whl下载地址: https://www.lfd.uci.edu/~gohlke/pythonlibs/
    其他的whl下载地址: https://pypi.org/project/numpy/#history
    然后pip install xxx.whl
  3. 权限的问题
    sudo pip install xxx
    sudo pip --user wang xxx

文件写入

f = open("log.txt","a+")  # 追加的方法写入,会自动创建新文件
print("hello",file=f)
f.flush()
f.close()
with open('test.txt','a') as file0:
    print( "hello" ,file=file0)

目录操作

import os
base = r'E:\数据集\miniImageNet'    # r表示会自动把\转为\\
os.chdir(base)

lst1 = os.listdir(base)

for file in os.listdir(base):
    print(file)

os.rename('oldname','newname') # 一定要事先os.chdir(base)

os.sep()  # 目录分隔符,win是'\\', linux是'/'

复制与移动

import shutil
import os 
 
os.chdir(r'E:\数据集\miniImageNet')
# 复制文件
shutil.copyfile('test.csv','test2.csv')
shutil.copyfile('test.csv','E:/test2.csv') 

# 移动文件
 shutil.move('test2.csv','E:/test.csv')

注意window下不能跨域分区,权限不够

kaggle上的miniImagenet数据集统一修改名字

# kaggle上的miniImagenet数据集同意修改名字
import os
import shutil
base = r'/content/drive/My Drive/miniImageNet/images_background' 
os.chdir(base)
count=0
newPath = r'/content/drive/My Drive/dataset/miniImageNet/imgs/'
for parent in os.listdir(base):
    os.chdir(base+'/'+parent) # 调到父亲文件夹下,并列出所有的图片
    for img in os.listdir():
        # 图片名称改为:父亲+自己
        newName = parent + img
        shutil.move( img , newPath+newName) # 移动到newPath下面并重命名为newName
        count+=1
print("重命名了",count,'个文件')

NumPy

学习链接: https://www.numpy.org.cn/index.html

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])   # 列表传递
b = np.array((0, 1, 2, 3, 4))  # 元组传递
c = np.arange(5)  # [0,1,2,3,4]
d = np.linspace(10,50,5)  # 10到50之间均匀搞5个数字
print(my_array)

print(my_array.shape)  # 打印我们创建的数组的形状: (5, ) 。意思就是 my_array 是一个包含5个元素的数组。

my_array[0] = -1
print(my_array[0])

my_new_array = np.zeros((5))  # 输出了 [0., 0., 0., 0., 0.]
# 还有np.ones
my_random_array = np.random.random((5))  # 5个随机值的数组,0~1之间

my_array = np.array([0,1,2,3,4])
my_array_column_2 = my_array[1:3]  # 切片左闭右开
print(my_array_column_2)

二维数组

# 二维数组
my_2d_array = np.zeros((2, 3))  # 2行3列全是0
# my_2d_array_new = np.ones((2, 4))  全是1
c = np.full((2,2), 7)  # 2x2数组全是数字7
e = np.eye(3)  # 3阶单位矩阵
d = np.diag([1,2,3]) # 对角矩阵

my_random_array = np.random.random((22))  # 2x2数组, 5个随机值的数组,0~1之间

print(my_2d_array[0][1])
print(a[0,1])  # 第0行第1列

my_array = np.array([ [4, 5,100], [6, 1],[1,2]])  # 数组里嵌套数组
print(my_array[0][2])

# 二维数组的切片
a = np.array([[11, 12, 13, 14, 15],
              [21, 22, 23, 24, 25],
              [31, 32, 33, 34, 35],
              [41, 42, 43, 44, 45],
              [51, 52, 53, 54, 55]])
print(a[0, 1:4]) # 第0行的[1,4)  >>> [12 13 14]
print(a[1:4, 0]) # [1,4)行的分别第0个   >>> [21 31 41]
print(a[::2,::2]) # >>>[[11 13 15]   隔行 隔列
                  #     [31 33 35]
                  #     [51 53 55]]
print(a[:,1]) #  冒号前后没有数字表示每一行都要,1表示第1列   >>>[12 22 32 42]


print(a.size) # >>>25
print(a.shape) # >>>(5, 5)

运算

import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])
b = np.array([[5.0, 6.0], [7.0, 8.0]])
sum = a + b
difference = a - b
product = a * b   # 逐元素乘法而不是矩阵乘法
quotient = a / b
matrix_product = a.dot(b)  # 矩阵乘法
print(matrix_product)

print(np.add(x, y))  # 和上面一样
print(np.subtract(x, y))
print(np.divide(x, y))
print(np.sqrt(x))

print(a.print(np.divide(x, y))())
print(a.min()) 
print(a.max()) 

np.transpose(arr)  # 转置
np.linealg.solve(arr,np.eye(n))  # 求arr的逆矩阵,n表示阶数

保存到磁盘

np.savetxt(X=arr,fname='D:/1.txt')  # 保存数组
b = np.loadtxt('D:/1.txt') 

pandas

在这里插入图片描述
在这里插入图片描述

Theano

先安装theano.
这是一个通用的符号计算框架,三个步骤: 定义符号变量,编译,传入数值计算


import theano
from theano import tensor as T

# 定义符号变量
x = T.scalar(name='input',dtype='float32')
w = T.scalar(name='weight',dtype='float32')
b = T.scalar(name='bias',dtype='float32')
z = w*x+b

# 编译模板
net_input = theano.function(inputs=[w,x,b],outputs=z)

# 传入数值计算
res = net_input(2.0, 3.0, 0.5)
print(res)

matplot库

import matplotlib.pyplot as plt

x = [1,2,3]
y = [5,7,4]
plt.plot(x,y,label='first line')
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x2,y2,label='second line')


plt.xlabel('x轴坐标,不能显示中文')
plt.ylabel('y轴坐标')
plt.title('标题,不显示中文')
plt.show()  # 一定要有这个

条形图和直方图

条形图

import matplotlib.pyplot as plt

# 创建条形图,color的 g 为绿色, b 为蓝色, r 为红,还可以用#191970,默认是蓝色
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()

在这里插入图片描述
直方图

import matplotlib.pyplot as plt

population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]

#  plt.hist ,你首先需要放入所有的值,然后指定放入哪个桶或容器,我们绘制了一堆年龄,并希望以 10 年的增量来显示它们,条形的宽度设为 0.8
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)

plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

在这里插入图片描述
散点图

import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8]
y = [5,2,4,2,1,4,5,2]
plt.scatter(x,y, label='skitscat', color='k', s=25, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

饼状图

import matplotlib.pyplot as plt
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Interesting Graph\nCheck it out')
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值