📅  最后修改于: 2023-12-03 15:06:23.863000             🧑  作者: Mango
在AI领域,有很多常用的代码,本文将介绍一些常用的代码片段,包括Python、C++和Java等语言。
在AI开发中,常用的库包括numpy、pandas、scikit-learn、tensorflow等。
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn import preprocessing
data = pd.read_csv('data.csv')
数据预处理包括标准化、归一化等操作。
scaler = preprocessing.StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
在AI中,常用的模型包括线性回归、逻辑回归、决策树、随机森林等。
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <algorithm>
typedef vector<double> vec;
typedef vector<vec> mat;
mat operator*(const mat &a, const mat &b) {
mat c(a.size(), vec(b[0].size()));
for (int i = 0; i < a.size(); i++)
for (int j = 0; j < b[0].size(); j++)
for (int k = 0; k < b.size(); k++)
c[i][j] += a[i][k] * b[k][j];
return c;
}
double cost(mat &X, vec &Y, vec &W) {
vec A = X * W;
vec B = Y - A;
return B * B / (2 * X.size());
}
vec gradient(mat &X, vec &Y, vec &W) {
vec g(X[0].size(), 0);
for (int i = 0; i < X.size(); i++) {
vec A = X * W;
vec B = A - Y;
for (int j = 0; j < X[0].size(); j++)
g[j] += B[i] * X[i][j] / X.size();
}
return g;
}
vec gd(mat &X, vec &Y) {
vec W(X[0].size(), 0);
double alpha = 0.01;
for (int i = 0; i < 1000; i++) {
W = W - gradient(X, Y, W) * alpha;
if (i % 100 == 0)
cout << cost(X, Y, W) << endl;
}
return W;
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);
Stream<String> stream2 = Stream.of("a", "b", "c");
IntStream stream3 = IntStream.range(1, 100);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream4 = list.stream();
Stream<String> stream5 = Stream.of("a,b,c", "d,e,f");
Stream<String[]> stream6 = stream5.map(s -> s.split(","));
Stream<String> stream7 = stream6.flatMap(Arrays::stream);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum1 = list.stream().reduce(0, Integer::sum);
int sum2 = list.stream().mapToInt(Integer::intValue).sum();
List<Integer> filteredList = list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());