通过矩阵运算求出参数融合的最佳参数

在做毕业设计时,求取到了一些图书的参数,然后打算通过模型融合来拟合用户的评分,我选取的办法是简单的参数融合。
整个分数矩阵记作X,则最佳系数为W,使得XW约等于Y
故对其进行矩阵运算
在这里插入图片描述
伪逆矩阵=(转置矩阵
矩阵)求逆*转置矩阵
代码如下:

# -*- coding: utf-8 -*-
import numpy as np

def main():
    print('learning...')
    input_x = []
    output_y = []
    with open("XX.txt","r",encoding="utf-8") as file:
        for line in file:
            line = line.replace("\n","")
            a,b,c = line.split(",")
            input_x.append([float(a),float(b),float(c)])
    file.close()

    with open("YY.txt","r",encoding="utf-8") as file:
        for line in file:
            y = line.replace("\n","")
            output_y.append(float(y))

	#matmul返回矩阵乘积,transpose矩阵转置,I操作符实现矩阵求逆
    log_x = input_x
    X_tag = np.mat(np.matmul(np.transpose(log_x), log_x)).I
    X_tag = np.matmul(X_tag, np.transpose(log_x))    
    weight =np.matmul(X_tag, output_y)
    print('weight is')
    print(weight)    
    print('Testing...')
    
    sqrt_variance = 0
    i = 0
    predict_price_list = [weight.tolist()[0]]
    
    for x in input_x:
        predict_price = np.matmul(x, weight) 
        value_x = x
        value_x.append(predict_price.tolist()[0][0])
        predict_price_list.append(value_x)          
        sqrt_variance += (output_y[i][0]-predict_price)**2        
        i += 1
    print('The sqrt variance is ' + str(sqrt_variance))        
        
if __name__ == '__main__':
    main()
发布了304 篇原创文章 · 获赞 51 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_39905917/article/details/105583430