You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多项式回归实现三角函数预测程序报错:类型不兼容问题求助

问题解决:多项式回归实现三角函数预测的ValueError修复

问题概述

编写了基于Python与scikit-learn的多项式回归程序,通过学习三角函数表CSV数据,实现输入角度输出对应sin、cos、tan值的功能,但运行时触发ValueError: dtype='numeric' is not compatible with arrays of bytes/strings.Convert your data to numeric values explicitly instead.,尝试转换数据类型仍未解决。

错误原因分析

  1. 用户输入未转换类型:input()函数返回字符串类型,直接传入模型的fit_transform方法时,scikit-learn无法将字符串识别为数值型数据。
  2. CSV数据类型问题:从CSV读取的角度列和三角函数值列可能被识别为字符串类型,未显式转换为数值型,导致模型训练和预测时出错。
  3. 重复训练冗余:每次调用sin/cos/tan函数都重新训练模型,既浪费资源又降低效率。

修复步骤

  1. CSV数据类型转换:读取CSV后,将角度列(第2列)和三角函数值列(第4-6列)转换为float类型,确保数据为数值型。
  2. 输入处理与校验:将用户输入的角度转换为float类型,同时添加输入校验,处理非数值输入的情况。
  3. 模型预训练:在程序初始化时一次性训练好三个模型,避免重复训练。

修复后的完整代码

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# 读取并预处理数据
path = r"C:\Users\todgu\Downloads\삼각함수표1111.csv"
doc = pd.read_csv(path, encoding="cp949")
doc = doc.dropna()

# 将数值列转换为float类型
x = doc.iloc[:, 1].astype(float).values.reshape(-1, 1)
y_sin = doc.iloc[:, 3].astype(float).values.reshape(-1, 1)
y_cos = doc.iloc[:, 4].astype(float).values.reshape(-1, 1)
y_tan = doc.iloc[:, 5].astype(float).values.reshape(-1, 1)

# 预训练三个模型
poly_reg = PolynomialFeatures(degree=4)
x_poly = poly_reg.fit_transform(x)

# sin模型
sin_reg = LinearRegression()
sin_reg.fit(x_poly, y_sin)

# cos模型
cos_reg = LinearRegression()
cos_reg.fit(x_poly, y_cos)

# tan模型
tan_reg = LinearRegression()
tan_reg.fit(x_poly, y_tan)

def predict_sin(angle):
    return sin_reg.predict(poly_reg.transform([[angle]]))

def predict_cos(angle):
    return cos_reg.predict(poly_reg.transform([[angle]]))

def predict_tan(angle):
    return tan_reg.predict(poly_reg.transform([[angle]]))

while True:
    print("<삼각함수 잘하는 AI>입니다.")
    print("이용하고자 하는 함수를 선택하세요.")
    print("[1] sin  |  [2] cos  |  [3] tan")
    func = input().strip()
    print("각도를 입력하여 주세요.(90°이하) [뒤로가기]")
    ang_input = input().strip()
    
    if ang_input == "뒤로가기":
        continue
    
    # 尝试转换角度为数值
    try:
        angle = float(ang_input)
        if angle > 90:
            print("각도는 90° 이하로 입력해주세요.")
            continue
    except ValueError:
        print("유효한 각도를 입력해주세요.")
        continue
    
    if func == "1" or func.lower() == "sin":
        print(f"sin({angle}) = {predict_sin(angle)[0][0]:.4f}")
    elif func == "2" or func.lower() == "cos":
        print(f"cos({angle}) = {predict_cos(angle)[0][0]:.4f}")
    elif func == "3" or func.lower() == "tan":
        print(f"tan({angle}) = {predict_tan(angle)[0][0]:.4f}")
    else:
        print("잘못된 입력값입니다.")

关键修复点说明

  • 路径前添加r前缀,避免转义字符问题。
  • 显式转换CSV数据为float类型,确保模型能处理数值数据。
  • 预训练模型,提升运行效率。
  • 添加输入校验,处理非数值输入和超出范围的角度,增强程序健壮性。
  • 预测时使用transform而非fit_transform,因为poly_reg已经在训练数据上拟合过。

内容的提问来源于stack exchange,提问作者TodGuess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:37:53