python 机器学习


一、数据准备

1.生成随机矩阵

import numpy as np
import random
import time

m = 10000
d = 200
k = 50

trains = np.zeros((m, d))
for i in range(m):
    trains[i] = np.array([random.gauss(0, 1) for z in range(d)])
test = np.array([random.gauss(0, 1) for z in range(d)])

print(trains.shape)

2.将表格转换为矩阵

import numpy as np
import xlrd
def excel_to_Matrix(path):
#读excel数据转为矩阵函数
    data = xlrd.open_workbook(path)
    table = data.sheets()[0]
    #获取excel中第一个sheet表
    nrows = table.nrows
    #行数
    ncols = table.ncols
    #列数
    datamatrix = np.zeros((nrows, ncols))
    for x in range(ncols):
        cols = table.col_values(x)
        cols1 = np.matrix(cols)
        #把list转换为矩阵进行矩阵操作
        datamatrix[:, x] = cols1
        #把数据进行存储
    return datamatrix
print(np.mat(excel_to_Matrix("表格.xlsx")))

二、常用函数

1.生成随机数

#生成1~100的随机int型
random.randint(1,100)
#选取不同的随机数
count = X.shape[0]
i = np.random.randint(0, count)
j = np.random.randint(0, count - 1)
j += (j >= i)

2.读出需要的行和列

import numpy as np
a = np.array([[1, 2], [3, 4], [5, 6]])
print(a)
i=[2,0]#在这里将i按顺序赋值为所需要的行号即可,比如本例中想要依次输出第2行和第0行
print(a[i,:])

3.txt与数组互相转换

# datafream2txt
X_train.to_csv(r"X_train.txt", sep='\t', index=False, header=False)
# ndarray2txt
numpy.savetxt(fname, X, fmt ='%.18e', delimiter ='', newline ='n', header ='', footer =", comments ='#', encoding = None)

参数:

  1. name : 文件名或文件句柄。如果文件名结束.gz,文件将自动以压缩gzip格式保存。 loadtxt透明地理解gzip文件。
  2. X : 1D或2D array_like。要保存到文本文件的数据。
  3. fmt : str或strs序列,可选。
  4. 分隔符 : str,可选。分隔列的字符串或字符。
  5. 换行符 : str,可选。字符串或字符分隔线。
# 保存二维数组
np.savetxt("matrix.txt", matrix, fmt="%d", delimiter=",")
# 读取二维数组
m = np.loadtxt("matrix.txt", dtype=int, delimiter=",")

4.对2d ndarray的列和行进行排序

data_cs = data[data[:, 1].argsort()] # 按第2列进行排序
data_rs = data[:, data[1].argsort()] #按第2行进行排序

总结

无。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值