python的shape和reshape_一文浅显易懂: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")

原文链接:https://blog.csdn.net/guangwulv/article/details/107897536

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值