该系列为Numpy入门,如无Python基础,请移步Python入门系列学习:Python3基础系列博文索引.



1.构造矩阵和向量
import numpy as np

matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
matrix2 = np.array([[4, 5, 6], [7, 8, 9]])

vector1 = np.array([[1], [2], [5], [8]])
vector2 = np.transpose(vector1)

print("matrix1矩阵内容:\n", matrix1)
print("---------------------------------------")

print("matrix2矩阵内容:\n", matrix2)
print("---------------------------------------")

print("vector1向量内容:\n", vector1)
print("---------------------------------------")

print("vector2向量内容:\n", vector2)
# 结果输出:
matrix1矩阵内容:
 [[1 2 3]
 [4 5 6]]
---------------------------------------
matrix2矩阵内容:
 [[4 5 6]
 [7 8 9]]
---------------------------------------
vector1向量内容:
 [[1]
 [2]
 [5]
 [8]]
---------------------------------------
vector2向量内容:
 [[1 2 5 8]]
2.用numpy求解方程组
# 求解Ax=b方程组
# 1.构建A和b的数组;
import numpy as np

A = np.array([[1, 2, 3],[4, 5, 6], [7, 8, 9]])
b = np.transpose(np.array([[6, 8, 4]]))

x = np.linalg.solve(A, b)

print("Ax = b方程组求解:\n", x)
# 结果输出:
Ax = b方程组求解:
 [[-1.89151184e+16]
 [ 3.78302369e+16]
 [-1.89151184e+16]]
3.多元线性回归实例:预测房价
# 实例:预测房价
import csv
import numpy as np

def readData():
    X = []
    y = []
    with open ("Housing.csv") as f:
        rdr = csv.reader(f)
        next(rdr)
        for line in rdr:
            xline = [1.0]
            for s in line[:-1]:
                xline.append(float(s))
            X.append(xline)
            y.append(float(line[-1]))
    return (X, y)


X0, y0 = readData()
d = len(X0) - 10
X = np.array(X0[:d])
y = np.transpose(np.array([y0[:d]]))

Xt = np.transpose(X)
XtX = np.dot(Xt, X)
Xty = np.dot(Xt, y)
beta = np.linalg.solve(XtX, Xty)
print(beta)

for data, actual in zip(X0[d:], y0[d:]):
    x = np.array([data])
    prediction = np.dot(x, beta)
    print("prediction = " + str(prediction[0, 0]) + " actual = " + str(actual))
# 结果输出:
[[-4.14106096e+03]
 [ 3.55197583e+00]
 [ 1.66328263e+03]
 [ 1.45465644e+04]
 [ 6.77755381e+03]
 [ 6.58750520e+03]
 [ 4.44683380e+03]
 [ 5.60834856e+03]
 [ 1.27979572e+04]
 [ 1.24091640e+04]
 [ 4.19931185e+03]
 [ 9.42215457e+03]]
prediction = 97360.65509691092 actual = 82500.0
prediction = 71774.16590136985 actual = 83000.0
prediction = 92359.08919760231 actual = 84000.0
prediction = 77748.274237906 actual = 85000.0
prediction = 91015.59030664092 actual = 85000.0
prediction = 97545.1179047323 actual = 91500.0
prediction = 97360.65509691092 actual = 94000.0
prediction = 106006.80075598106 actual = 103000.0
prediction = 92451.69312694679 actual = 105000.0
prediction = 73458.29493810149 actual = 105000.0
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐