如何使用python计算单个矩阵值的平方?

2024-09-28 21:36:56 发布

您现在位置:Python中文网/ 问答频道 /正文

用Python实现的代价函数: **谢谢你的帮助。你知道吗

import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
    feature_vale = load_data[0]
    y = np.matrix(load_data[1])
    m = len(feature_vale)
    plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
    plt.title("Cost_Function")
    plt.xlabel("Population of City in 10,000s")
    plt.ylabel("Profit in $10,000s")
    df = pd.DataFrame(pd.Series(1,index= range(0,m)))
    df[1] = load_data[0]
    X = np.matrix(df)
    row_theta = np.zeros(2,dtype = int)
    theta = np.array([row_theta]) # Transpose the array
    prediction = np.dot(X,theta.T)
    error = (prediction-y.T)
    error_df = pd.DataFrame(error)
    #square the error
    squared_error = np.square(error_df)
    sum = np.sum(squared_error)
    print(sum)
    J = np.sum(squared_error) / (2 * m)
    print(J)

数据参考链接:searchcode.com/codesearch/view/5404318你知道吗


Tags: importdfdataasnploadplterror
1条回答
网友
1楼 · 发布于 2024-09-28 21:36:56

重复以下步骤并通知我

load_data = pd.read_csv('data.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
#print(m)
#plt.scatter(load_data[0],load_data[1])
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
print(theta.T)
prediction = np.matmul(X,theta.T)
error = (prediction-y)
error_df = pd.DataFrame(error)
squared_error = np.square(error_df)
print(squared_error)

相关问题 更多 >