首页 > 解决方案 > 如何使用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

标签: pythonpandasnumpymachine-learningscipy

解决方案


重复以下步骤并告诉我

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)

推荐阅读