shape与reshape

shape()和reshape()都是数组array中的方法

shape :英文翻译为 形状

在矩阵中是读取矩阵的行数和列数的信息。

reshape : 英语翻译为 重塑、改变…的形状

在矩阵中是改变数组arr的矩阵形式。

代码在Python3.6版本或者Pycharm上运行。

1、shape的用法

import numpy as np

a = np.array([1,2,3,4,4,3,2,8]) #一维数组

a1 = np.array([[1,2,3,4],[4,3,2,8]]) #二维数组

print(a.shape[0]) #值为8,因为有8个数据

print(a1.shape[0]) #值为2(2行)

print(a1.shape[1]) #值为4(4列)

 

由上代码可以看出:

一维数组的时候:shape是读取数组的数据个数。

二维数组的时候:shape[0]读取的是矩阵的行数,shape[1]读取的是矩阵的列数。

2、reshape的用法

import numpy as np

a = np.array([1,2,3,4,4,3,2,8]) #一维数组

print(a.reshape(2,4) )

#输出结果为:[[1 2 3 4]

# [4 3 2 8]]

print(a.reshape(3,3))

#ValueError: cannot reshape array of size 8 into shape (3,3)

 

由上列代码可以看出:

reshape(m,n)将原矩阵改变为m行n列的新矩阵,但是新矩阵数据如果超过了原来数据的索引范围就会报错。

# 训练集和测试集数据

X_train = [[6], [8], [10], [14], [18]]

y_train = [[7], [9], [13], [17.5], [18]]

X_test = [[7], [9], [11], [15]]

y_test = [[8], [12], [15], [18]]

# 画出横纵坐标以及若干散点图

plt1 = runplt()

plt1.scatter(X_train, y_train, s=40) #每个点的size是40

# 给出一些点,并画出线性回归的曲线

xx = np.linspace(0, 26, 100) #0-26之间等间隔生成100个点作为XX的横轴

regressor = LinearRegression()

regressor.fit(X_train, y_train)

yy = regressor.predict(xx.reshape(xx.shape[0], 1)) #预测100个点的横坐标得到yy

#shape[0] 第一维(行)的长度(行数)

#shape[1]为列数

#reshape((2,4)) 改成2行4列矩阵

plt.plot(xx, yy, label="linear equation")

-1为未指定,用于无需指定行数或列数情况

 

引用:https://blog.csdn.net/weixin_39998859/article/details/110681888?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-0.base&spm=1001.2101.3001.4242

 

posted @ 2021-07-22 13:20  KAVEI  阅读(442)  评论(0编辑  收藏  举报