shape: the English translation of the shape
information of the number of rows and columns in the matrix is read matrix.
reshape: English translation is remodeling ... change the shape of
the matrix is to change the form of a matrix array arr.
The code runs on Python 3.6 version or Pycharm.
1. The usage of 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列)
It can be seen from the above code: when
a one-dimensional array: shape is the number of data read in the array.
In the case of a two-dimensional array: shape[0] reads the number of rows of the matrix, shape[1] reads the number of columns of the matrix.
2. The usage of 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)
It can be seen from the above code:
reshape(m,n) changes the original matrix to a new matrix with m rows and n columns, but if the new matrix data exceeds the index range of the original data, an error will be reported.
3. Examples of mixed use of shape and 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")