一文浅显易懂:Python中shape()和reshape()的用法和区别

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列的新矩阵,但是新矩阵数据如果超过了原来数据的索引范围就会报错。

3、shape和reshape混合使用的例子:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from matplotlib.font_manager import FontProperties   #导入字体属性模块

font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=20)  #设置字体为宋体


def runplt():    #设置生成画图的函数
    plt.figure()  # 定义figure
    plt.title(u'披萨的价格和直径', fontproperties=font_set)
    plt.xlabel(u'直径(inch)', fontproperties=font_set)
    plt.ylabel(u'价格(美元)', fontproperties=font_set)
    plt.axis([0, 25, 0, 25])
    plt.grid(True)  #画网格线
    return plt


# 训练集和测试集数据
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")

猜你喜欢

转载自blog.csdn.net/guangwulv/article/details/107897536